Giter Site home page Giter Site logo

sphilee / jspdf-customfonts-support Goto Github PK

View Code? Open in Web Editor NEW
183.0 20.0 77.0 68.2 MB

This repo is being deprecated. Please check out https://github.com/MrRio/jsPDF

Home Page: https://github.com/MrRio/jsPDF

License: MIT License

JavaScript 100.00%
jspdf jspdf-customfonts-support

jspdf-customfonts-support's Introduction

jspdf-customfonts-support's People

Contributors

hackbrettxxx avatar sphilee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jspdf-customfonts-support's Issues

Rotating Text

Hi,
I had an issue where text would not rotate with a custom font using this library. I resolved by modifying the APi.text method

Below transformationMatrix = [f2(c), f2(s), f2(s * -1), f2(c)];

I added
xtra = [f2(c), f2(s), f2(s * -1), f2(c), ''].join(" ") + "";
mode = 'Tm';

I declared mode at the top of method and initialised to Td

I then modified the args passed into the out function as folllows:

out('BT\n/' + activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
activeFontSize * lineHeightProportion + ' TL\n' + // line spacing
textColor + '\n' + xtra + f2(x * k) + ' ' + f2((pageHeight - y) * k) + ' ' + mode + '\n' + text + ' Tj\nET');

(added xtra and modified mode)
Looks to be working for me, hope this helps somebody!

Incorrect characters pulled from custom font

Using: https://sphilee.github.io/jsPDF-CustomFonts-support/# with this font
baloo-tamma-v3-latin.zip
Downloaded from here: https://google-webfonts-helper.herokuapp.com/fonts/baloo-tammudu?subsets=latin
With the following code:
`
doc.addFont('baloo-tamma-v3-latin-regular.ttf', 'custom', 'normal');

doc.setFont('custom');
doc.text(15, 15, 'ABCDEFabcdefgAAAAAAAAAAAAAAAAAAAB');
`

Gnerates a pdf with the following text:
!"#$%&'()*+,-!!!!!!!!!!!!!!!!!!!"

demo (2).pdf

Base64 decoding the file using https://www.base64decode.org/ generates a ttf file which looks correct so it can't be the font data.

How to support and add multiple font files?

Hi,

As i want to use google Noto and Google CJK fonts for PDF generation.but all have different ttf files.so how i can i convert and give single ttf base 64 encoded files to jspdf custom font support?
please help,as this is urgent.
@sphilee

Standard WinAnsiEncoding fails with € sign

but works perfectly fine with $ sign, accents, etc.
The font used is Montserrat but also other fonts such as open sans are giving the same problem.

This is what happens (it draws weird characters on all the line of text) http://prntscr.com/g4cyzq

Also, if I try to change the encoding to Identity-H the generated PDF cannot be read.

webpage become slow as font file becomes big with unicode.

Hi,

As i am using Arial_Unicode fonts for pdf generation.but with that the vfs_fonts.js becomes around 30 MB to load in webpage,which makes webpage a slower to load.

is there any solution for font file to compress and still support in pdf??

Buggy output when opened with muPDF

When an external font is embedded in the PDF, it cannot be opened in muPDF correctly:
jspdf-mupdf-font
Expected output:
jspdf-evince-font

muPDF also logs the following:

error: freetype: cannot load font: invalid stream operation
warning: ignored error when loading embedded font; attempting to load system font

The code to embed the fonts is as follows:

const pdf = new jsPDF();
pdf.addFileToVFS("Roboto-Regular.ttf", ROBOTO);
pdf.addFileToVFS("Roboto-Bold.ttf", ROBOTO_BOLD);
pdf.addFont("Roboto-Regular.ttf", "Roboto", "normal");
pdf.addFont("Roboto-Bold.ttf", "Roboto", "bold");

Here is the PDF in question:
hyperschedule-color.pdf

Other PDF viewers can open the file correctly, so this may be a problem with muPDF. On the other hand, muPDF has also been fine with opening other PDFs with embedded fonts in the past, so I think the problem is not with only muPDF. I suspect that there is some protocol that this library is not following entirely and that other PDF viewers have managed to correct for these errors in a way that muPDF hasn't.

cannot read property 'Unicode' of undefined

Hi, I have success loading font with this plugin, however, it gives me a problem when trying to do splitTextToSize(). I got an error message: can not read property 'Unicode' of undefined. While I am using built-in fonts, it just running fine.

In order to load custom fonts, I am using node makeFonts.js approach.

Here is the font which I used: https://fonts.google.com/specimen/Nunito+Sans . Is there any clue what kind of fonts that I can use with this plugin?

Any help will be highly appreciated. Thank you in advance.

update readme?

Hey just want to confirm... I think the main jspdf lib incorporated custom font support directly without the need for this package any longer, as of 1.5. Unless I'm missing something. Is that correct? I removed this package after updating and everything seems to be working. I guess this package remains just to support projects still using jspdf 1.4 and under. Maybe the documentation should be updated? Would be happy to do so if the above is correct

Plan on adding custom fonts? (Feature Request)

Hello there,

first of all, thanks for this great effort to add arbitrary fonts to jsPDF. We are currently integrating this plugin into our fork https://github.com/yWorks/jsPDF in order to be able to use custom fonts with svg2pdf.js.

We are quite happy with the progress this project is making recently. However, we miss the functionality to comfortably add custom fonts. Either at runtime on the browser or with a small build tool that generates a file like "defaultVFS.js" from font files. What would also be great is support for other font formats like WOFF/WOFF2 or SVG-Fonts.

What are your plans concerning this features?

Greetings,
Hackbrett

autoTable을 이용한 한글 출력

안녕하세요? @sphilee

올려주신 예제 활용해서 한글까지 출력은 했습니다.
html table에 있는 데이터를 pdf표로 그리고 싶은데,
autoTable을 이용하니 여전히 한글이 깨지더라구요.

방법이 없을까요??
image

Thai language Support ?

Hi there.
I have use js-customfonts to add THSarabunNew font , I already test with add with file base64 encrypt and add with .ttf file type when i checked console.log it show the same error. this is an error message
Uncaught TypeError: Cannot set property 'adler32cs' of undefined at t (jspdf.customfonts.min.js:102) at jspdf.customfonts.min.js:102 at jspdf.customfonts.min.js:1 at jspdf.customfonts.min.js:1

custom fonts with html

how can we use custom fonts while creating pdf from html
I see the current way of converting html to pdf with jspdf is based on converting a canvas created by html2canvas to the pdf. but how can custom fonts be used in that scenario?

Cannot read property 'widths' of undefined

I am trying to center the text but I am getting this error when using the function getStringUnitWidth.
I already included the required plugins:

  • split_text_to_size.js

When I use the script from jsPDF, the error disappears but the font doesn't work.

Optimizing pdf file size

Hello,

currently, when I add a font, it is included into the final pdf file as a whole. Is this right? Would it be possible to only include characters or character ranges that are actually used?

I suppose this would massively reduce the file size. Especially if one adds a huge font as fallback-font that supports the whole Unicode range.

Greetings

Custom Font not working in Firefox

Hi
I had problems with displaying the €-Character with the Standard Fonts, so i decided to use Custom Fonts. It worked perfectly in Chrome, but the Problem is, that Firefox doesn't create my PDF with Custom Fonts, displaying these Errors:

"No unicode cmap for font"
"font.metadata.Unicode is undefined"

I use PTSans (Regular,Bold,Italic), but also tried other free Unicode-Fonts, who led to the same Errors.
I also debugged the jspdf.debug.js and saw, that the TTFFont Function in Chrome and Firefox differ, for example they have different values in data.readString(4) which leads to a broken cmap value in Firefox.

Does anyone ever faced this problem, or maybe knows a fix?

Text alignment `right`and `center` not working

if you change the 6th line at the demo page to
doc.text(90, 15, 'こんにちは。はじめまして。', null, null, 'right');
the font looks kind of strange.

If you change the font to helvetica, the alignment works as aspected.

Is there any way to use this library and also using addImage function ?

I'm need to create pdf that contain my canvas image (that i already take by document query selector and after that adding it by doc.addImage). The problem that I occured is that, when i starts using custom fonts, i can't use addImage function.

Is there any way that I can solve my problem, and I will by able to use custom font and also add my canvas image to generated pdf ?

Missing characters

image

image

It seems working well at first but after writing several lines, some characters go invisible.

I've tested with some other fonts (NanumBareunGothic, Spoqa Sans...) and all of these cases show same problem... (Code above was modified from one you posted on issue #24 )

Does this happen only for me? Can you please check it?

Font spacing on PDF file

Hello, first of all thank you for this awesome feature!

So far the only issue I'm having is that It looks like the kerning in many fonts is way too off.

If someone know how to fix this I will really appreacitae the help, thank you!

example.png

FromHTML custom font

Hi, actually I used the code example, but when I try to use a personalized font, this doesn't work whit fromHTML function.

I saw the code inside jspdf.customfonts.debug.js and I think that the issue can be inside the ResolveFont function, this because this function always returns font-family "times", nevertheless other css properties works correctly (color for example).
this is my code:

I added the PersonalizedFont.ttf file to the fonts folder and also I modified the default_vfs.js file whit my font in base64, in this case the doc.text(15, 15, 'Hello world'); takes the correct font but the, doc.fromHTML does't.

Could you please help whit this problem.

$(document).ready(function () {

            var doc = new jsPDF();

            var specialElementHandlers = {
                '#editor': function (element, renderer) {
                    return true;
                }
            };

            $('#cmd').click(function () {

                var doc = new jsPDF();
                doc.addFont('PersonalizedFont.ttf', 'PersonalizedFont', 'normal');
                doc.setFont('PersonalizedFont');
                var html = "<!DOCTYPE html>\
                                <html>\
                                <head>\
                                        <style>\
                                            @font-face {\
                                                font-family: GamjaFlower;\
                                                src: url('./fonts/PersonalizedFont.ttf');\
                                                font-weight: bold;\
                                            }\
                                            p   {\
                                                    font-family: GamjaFlower;\
                                                    color: blue;\
                                                }\
                                        </style>\
                                </head>\
                                <body>\
                                 <p>\
                                        Lorem ipsum dolor sit amet, consectetur adipisicing elit,\
                                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\
                                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris\
                                        nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\
                                        in reprehenderit in voluptate velit esse cillum dolore eu fugiat\
                                        nulla pariatur. Excepteur sint occaecat cupidatat non proident,\
                                        sunt in culpa qui officia deserunt mollit anim id est laborum.\
                                        Hola mundo FromHTML\
                                        </p>\
                                </body>\
                                </html>";
                doc.fromHTML(html, 15, 15, {
                    'width': 170,
                    'elementHandlers': specialElementHandlers
                });


                doc.addFont('PersonalizedFont.ttf', 'PersonalizedFont', 'normal');
                doc.setFont('PersonalizedFont');
                doc.text(15, 15, 'Hello world');
                doc.save('PersonalizedFont.pdf');
            });
        });

How to use Custom Fonts?

I tried adding Roboto font.

doc.addFont('Roboto-Regular.ttf', 'roboto', 'normal', 'Identity-H'); doc.setFont('roboto');

But it doesn't seem to work? What is the issue here?

Also, how can I use Google Web Fonts? I read that it should be possible by converting font to base64 format but I couldn't find any working implementation or couldn't get to convert google web fonts to base64 format.

Any ideas?

Working on all browsers except Chrome on Windows

I am using this library which I think is great. Makes jsPDF very usuable.
I have a problem however with custom fonts only on Windows Chrome Browser. On Windows Edge and Firefox everything is working as expected. Even Chrome on OSX and Android is working. Problem is Chrome Windows users are the majority and I would like a few pointers if you can help me out here.

The Chrome Console gives the following output:

https://drive.google.com/file/d/1CUYQAYN2ORjxfCsCkMq4bet16dkiNpWo/view?usp=sharing

React Customfonts

How can i import this in react . It says

doc.addFileToVFS is not a function

jsPDF Autotable Error

Error when used with Autotable.

Only added autotable and tried to export

    <script>
        var doc = new jsPDF();

        doc.addFont('HMKMMAG.TTF', 'MagicR', 'normal', 'Identity-H');
        doc.addFont('HMKMRHD.TTF', 'HeadlineR', 'normal', 'Identity-H');
        doc.addFont('msgothic.ttf', 'MsGothic', 'normal', 'Identity-H');
        doc.addFont('gothic.ttf', 'LiLing', 'normal', 'Identity-H');
        //doc.addFont('HARLOWSI.TTF', 'WMLWQI+HarlowSolid', 'normal', 'WinAnsiEncoding');
        //doc.addFont('ITCBLKAD.TTF','a','normal','WinAnsiEncoding');
        //doc.addFont('BOD_PSTC.TTF','b','normal','WinAnsiEncoding');
        //doc.addFont('GADUGI.TTF', 'GADUGI', 'normal', 'WinAnsiEncoding');



        doc.setFont('MagicR');        // set font
        doc.setFontSize(20);
        doc.setTextColor(153,051,102);
        doc.setCharSpace(3);

        //doc.setDefaultFonts(0, 'Times');    //English default
        //doc.setDefaultFonts(1, 'MagicR');    //Korean default
        doc.setDefaultFonts(3, 'LiLing');         //Chinese default
        doc.setDefaultFonts(2, 'MsGothic');        //Japanese default



		var columns = ["ID", "Name", "Country"];
		var rows = [
    		[1, "Shaw", "홍A平길Bお동安C"],
    		[2, "Nelson", "Kazakhstan"],
    		[3, "Garcia", "Madagascar"],
		];

		doc.autoTable(columns, rows,{styles: {font: "MsGothic"}});
		doc.save('table.pdf');
    </script>

got below error

Uncaught TypeError: Cannot read property 'widths' of undefined
at Object.API.getCharWidthsArray (split_text_to_size.js:47:89)
at Object.API.getStringUnitWidth (split_text_to_size.js:95:40)
jspdf.plugin.autotable.js:311:57
at Array.forEach (native)
at Object.getStringWidth (jspdf.plugin.autotable.js:310:10)
spdf.plugin.autotable.js:964:71
at Array.forEach (native)
jspdf.plugin.autotable.js:962:44
at Array.forEach (native)
at Object.calculateWidths (jspdf.plugin.autotable.js:960:19)

Problem when aligning text

Hello, first thanks for your great plugin!

I got my ".ttf" fonts added to jsPDF, and working. But your version of jsPDF have issues with text alignment.

doc.text(190, 76, "SomeText", 0, "right");
Do not work in your version of jsPDF, but works fine in the new debug version of jsPDF (version 1.3.5), I have not been able to use your plugin with the debug version, could anyone inform me what to do, implement your plugin with jsPDF 1.3.5 debug?

When using alignment of the text(with your version of jsPDF v1.3), I will get an error like: "Uncaught TypeError: Cannot read property 'width' of undefined" from split_text_to_size.js on line 47

Export SVG charts using html2canvas + jsPDF + jspdf.customfonts.js

Hi i need to export a SVG chart with custom fonts using 3 components, i am a able to do with html2canvas and jsPDF but custom fonts not exporting in jsPDF hence using your jspdf.customfonts.js but it is throwing error, and not applying custom fonts. i used your run book steps but in vain.

Please advise
ERROR:
jspdf.debug.js:160 jsPDF PubSub Error No unicode cmap for font Error: No unicode cmap for font
at t.registerTTF (jspdf.customfonts.min.js:9)
at new t (jspdf.customfonts.min.js:9)
at Function.t.open (jspdf.customfonts.min.js:9)
at Object. (jspdf.customfonts.min.js:9)
at PubSub.publish (jspdf.debug.js:157)
at addFont (jspdf.debug.js:647)
at Object.API.addFont (jspdf.debug.js:2374)
at Object.onrendered (realtimectrl.js:425)
at jspdf.debug.js:15229

jspdf.debug.js:160 jsPDF PubSub Error Cannot read property 'advance' of undefined TypeError: Cannot read property 'advance' of undefined
at jspdf.customfonts.min.js:9
at Array.map ()
at o (jspdf.customfonts.min.js:9)
at t.embedTTF (jspdf.customfonts.min.js:9)
at Object.e.putFont (jspdf.customfonts.min.js:9)
at PubSub.publish (jspdf.debug.js:157)
at putFont (jspdf.debug.js:541)
at putFonts (jspdf.debug.js:564)
at putResources (jspdf.debug.js:588)
at buildDocument (jspdf.debug.js:1042)

jspdf.debug.js:160 jsPDF PubSub Error e.metadata.embedTTF is not a function TypeError: e.metadata.embedTTF is not a function
at Object.e.putFont (jspdf.customfonts.min.js:9)
at PubSub.publish (jspdf.debug.js:157)
at putFont (jspdf.debug.js:541)
at putFonts (jspdf.debug.js:564)
at putResources (jspdf.debug.js:588)
at buildDocument (jspdf.debug.js:1042)
at getArrayBuffer (jspdf.debug.js:1106)
at getBlob (jspdf.debug.js:1116)
at Object. (jspdf.debug.js:1145)
at Object.__safeCallWrapper [as output] (jspdf.debug.js:679)

Regarding Urdu/Arabic Font

Thanks for contribution. I want to asked is it support urdu/arabic font. please confirm its very urgent

doesn't jspdf support it now?

I have seen examples using only jspdf that add custom fonts in this way:

doc.addFiletoVFS('font.ttf', base64value)
doc.addFont(...)
doc.setFont(...)

and it works
so what is the need to this project anyway?

I have an inquiry about Korean support. 한국어가 투명합니다.

안녕하세요, 이 기능을 적용하려고 테스트 중입니다.

cjk 폰트는 한국어를 지원하는 것으로 알고 있습니다.

그러나 한국어를 사용하면 한국어는 투명하게 나오는 것으로 보입니다. 드래그로 복사하여 다른 곳에 붙여 넣으면 확인할 수 있습니다.

올려주신 데모에서도 한국어는 투명하게 나오는데 한국어 지원이 현재 안되는 것인가요?


Hello, I am testing to apply this feature.

I know that the cjk font supports Korean.

However, if you use Korean, it seems that Korean is transparent. Copy it to a drag and paste it elsewhere.

In the demo you uploaded, the Korean language is transparent, does not Korean support now?

image
image

Reason for not forking?

Just wondering if you had a reason for not forking jspdf instead of starting from scratch?

Anyhow, will be following this intently. Great initiative!

Make CustomFonts into a plugin

Hi,

Thank you very much for your solution. I can see that you clearly understand how to work with jspdf.
I have a request for your solution.

At the moment it seems like this is a fork of a version of jspdf. The customfonts solution is integrated into the fork. I used to have a separate jspdf dependency in my project along with some plugins. Now I need to switch the jspdf dependency with the customfonts dependency (because jspdf library is in customfonts).

It would be really nice to use customfonts as a plugin instead of a replacement for the entire jspdf library. Because I then have the freedom to down- or upgrade jspdf library.

I don't mind if you want me to help make customfonts into a plugin. Just give me few pointers on how to go about it.

regards,
Rafiek

Additional information if custom font has not been imported

I started to use that great library within my Angular 4+ project. After I made a test with 'demo' files I implemented library to my source code.
First usage and error occured. I the end it was a problem with custom font import.

Based on that I propose small improvements, add extra information for Developer who will meet similar problem like me.

1. extend following push with console.error

jsPDFAPI.events.push(['addFont', function(font) {
    if (jsPDFAPI.existsFileInVFS(font.postScriptName)) {
        font.metadata = TTFFont.open(font.postScriptName, font.fontName, jsPDFAPI.getFileFromVFS(font.postScriptName), font.encoding);
        font.encoding = font.metadata.hmtx.widths.length < 500 && font.metadata.capHeight < 800 ? "WinAnsiEncoding" : "MacRomanEncoding";
    } else {
        if (font.id.slice(1) >= 14)
        console.error(`Font does not exist in FileInVFS, import fonts or remove declaration doc.addFont('${font.postScriptName}').`)
    }
}]);

Result
image

2. Stop further code execution if missing fonts

var getCharWidthsArray = API.getCharWidthsArray = function(text, options) {

    if (!options) {
        options = {};
    }

    var l = text.length;
    var output = [];
    var i;
    var isEmpty = Object.keys(options.font).length === 0 ? true : false;

    // Stop here if empty
    if (isEmpty) {
        return false;
    }

3. No error with embedTTF

putFont = function putFont(font) {
    var noMetadata = Object.keys(font.metadata).length === 0 ? true : false;
    if (font.id.slice(1) >= 14 && !noMetadata) {
        var dictionary = font.metadata.embedTTF(font.encoding, newObject, out);
        dictionary ? font.objectNumber = dictionary : delete fonts[font.id];
    } else {
        font.objectNumber = newObject();
        out('<</BaseFont/' + font.postScriptName + '/Type/Font');
        if (typeof font.encoding === 'string') {
            out('/Encoding/' + font.encoding);
        }
        out('/Subtype/Type1>>');
        out('endobj');
    }
},

Error in IE when user customfont

ERROR: jsPDF PubSub Error Object doesn't support property or method 'toString' TypeError: Object doesn't support property or method 'toString'.

I have my code
const pdf = new jsPDF('l', 'mm', 'a3');
let base64Str = 'AAEAAAANAIAAAwBQRkZUTXas8jIADxLYAAAAHEdERUYAKR.....';
pdf.addFileToVFS('NotoSansCJKjp-Regular.ttf', base64Str);
pdf.addFont('NotoSansCJKjp-Regular.ttf', 'NotoSansCJKjp', 'normal');
pdf.setFont('NotoSansCJKjp');
pdf.setFontSize(12);
pdf.text('取引報告書及び仮想通貨管理明細簿兼残高報告書', 15, 20);
pdf.save('test.pdf');

base64Str i get in https://raw.githubusercontent.com/sphilee/jsPDF-CustomFonts-support/master/dist/default_vfs.js

please help me

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.