Setting styles for embedded fonts in jsPDF - jspdf

i have an issue with generating pdfs in regards to embedding fonts. I just used
pdf.addFileToVFS('Acme-Regular-italic.ttf', fontBase64Data);
pdf.addFont('Acme-Regular-italic.ttf', 'Acme', 'italic');
pdf.setFont("Acme", 'italic');
pdf.text("italic Acme", 10, 10);
pdf.addFileToVFS('Acme-Regular.ttf', fontBase64Data);
pdf.addFont('Acme-Regular.ttf', 'Acme', 'normal');
pdf.setFont("Acme", 'normal');
pdf.text("regular Acme", 10, 40);
pdf.addFileToVFS('Acme-Regular-bold.ttf', fontBase64Data);
pdf.addFont('Acme-Regular-bold.ttf', 'Acme', 'bold');
pdf.setFont("Acme", 'bold');
pdf.text("bold Acme", 10, 70);
where fontBase64Data is always the Acme.ttf encodes as base64
and the font i see for the three variants is always the same!? So I wonder what I am missing. Do I need to pass different base64 encodingds (one for regular, one for bold...) - whcih I don't have? If so where can I get those?
Here the result i get as screenshot from pdf:
Cheers
Tom

Base64 is one input file one output file so if its built from command
base64 -e upright.ttf fontBase64.Data
then on decoding that string it can only be one single upright.ttf
For each family style you wish to embed you will need separate font ttfs
normal.ttf
italic.ttf
bold.ttf
bold italic.ttf
the preferred method is supply the regular/normal.ttf italic/oblique.ttf and bold/heavy.ttf etc. to the converter per the web site method
https://rawgit.com/MrRio/jsPDF/master/fontconverter/fontconverter.html
but do read the instructions at https://github.com/parallax/jsPDF#use-of-unicode-characters--utf-8
in return you will get the base64 style in a js wrapper
one advantage of holding the data in a referenced fontstyle.js is that the decompressed ttfs do not need to be included inline on the pdf building html page just linked like any other resource.

Related

How to set font in Texinfo

I'm using the GNU texinfo package to generate both PDF and .info files from a .texi file.
I'm trying to update an old .texi file (not changed since 2001) and generate the same PDF output. I've resolved a number of issues, but there are a couple outstanding. In the old PDF, the title was in Helvetica and body text is Liberation Serif. In the new PDF, both are Computer Modern.
I've read everything that I can find about fonts, but I'm not able to change the fonts. Nothing that I do seems to work. Everything I have tried generates errors.
In my .texi file, before any \setfont directives, I have \def\fontprefix{uh} which, if I read the pdftex.map file correctly, should select the NimbusSanL font set (e.g. uhvr8a.pfb). I get the following errors:
mktexnam: Could not map source abbreviation for uhss10.
kpathsea: Running mktexmf uhss10
! I can't find file uhss10'.
<*> ...ljfour; mag:=1; ; nonstopmode; input uhss10`
Does anyone have a example .texi file which sets the font family to use? Or an explanation of what I'm doing wrong?

TCPDF Embedded Base64 Encoded Images in HTML String

I have read several posts on this subject but didn't want to piggy-back on any of them with additional questions.
Specifically this post: TCPDF and insert an image base64 encoded
I am generating a PDF from within a custom theme in Wordpress. I'm using TCPDF 6.2.3 (latest stable release, I believe).
I am building this PDF from the same HTML I am using to display on the page. If I embed the full base64 encoded string, it works correctly in the browser, but the image is missing from the PDF.
If I use the "#" method described in the linked post, I get a broken image in the browser (expectedly) but still nothing in the PDF.
All the rest of my HTML markup is rendering in the PDF, images are just not showing.
Is there some other setting or option I need to set in order to get the images to appear in the PDF, and/or can you spot anything I'm doing wrong here? No errors, the images are just not visible in the PDF.
This is how I set the image up:
$imageLocation = $img_root.$imgsrc;
$ext = end(explode(".", $imageLocation));
$image = base64_encode(file_get_contents($imageLocation));
//$response .= "<img src='data:image/$ext;base64,$image'>"; //works in browser but not in PDF
$response .= "<img src='#$image' class='socf_image'>"; //does not work in browser or PDF
And here is the method to create the PDF:
function createPDF($response)
{
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_6_3_2/tcpdf/tcpdf.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('test');
$pdf->SetTitle('test');
$pdf->SetSubject('test');
$pdf->SetKeywords('test');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING, array(0,64,255), array(0,64,128));
$pdf->setFooterData(array(0,64,0), array(0,64,128));
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set default font subsetting mode
$pdf->setFontSubsetting(true);
// Set font
$pdf->SetFont('helvetica', '', 14, '', true);
// Add a page
$pdf->AddPage();
$html = $response;
$pdf->writeHTML($response, true, false, true, false, '');
return $pdf;
}
Well, fortunately, I was able to figure it out on my own. Perhaps this isn't the best forum for seeking help with this library? If anyone can suggest a better place to get help, I'd appreciate the direction.
Ultimately, the issue was two-fold:
The "#" notation is required for the PDf while the approach is what works for displaying the HTML in browser. So a string replace before creating the PDF solves that.
This is the tricky part. The HTML needs to use double-quotes around the properties, not single quotes. My code was using double quotes for the PHP strings, so the HTML properties were surrounded with single quotes and that was the issue. Swapping the two quote types was the last piece of the puzzle to get the images to appear in the PDF.
Hopefully this will help someone else who is pulling their hair out trying to blindly find their way through this library like me.

Rails/Ruby save image as base64 and access it in the views

I would like to know can we convert a image into base64 and save it in a database and access it in the views.
I have searched google and stackoverflow, all of them starts from middle like encoding or displaying the image.
I need to know how can we convert a image url/path(lets say i store image inside my app and its url stored in column)
How to encode it as base64 before saving(should we convert to base64 first and save in db?).
How to display it in the views
You can split this task to three or four steps:
getting the image
encoding to base64
storing it in database (optionaly)
display it in views
Getting the image
From Assets pipeline
If you are using Rails asset pipeline for that, you can use Rails.application.assets hash to get to image: Rails.application.assets['image_name.png'].to_s will give you the content of image_name.png image.
from file - local or by url
Here is the question about that on StackOverflow.
encode
Base64 Ruby module docs tells how to use Base64 encoding in Ruby:
Base64.strict_encode64(your_content_here)
NOTE: in this case strict_encode64 is preferrable over just encode64 because it doesn't add any newlines. (credit goes to Sergey Mell for pointing that out)
From docs:
encode64 - ... Line feeds are added to every 60 encoded characters.
strict_encode64 - ... No line feeds are added.
Store it in database (optionaly)
I suggest you to create a separate ActiveRecord model for that, with field of type text to keep base64 representation of image.
Display it in views
You can provide data-url to src attribute of img tag, so, the browser will decode image from base64 and display it just like regular image:
<img src="data:image/png;base64,YOUR_BASE64_HERE"/>
Don't forget to change image format to whatever format you are using in data:image/png section.
UPDATE (2018-08-22): I have tried to use urlsafe_encode64, as suggested by Xornand, and for me it produces the output that is not recognized as image by the browser.
Tried in both Firefox 61.0.2 and Chromium 68.0.3440.106.
For the sake of reference and to enable experimentation, here are results themselves.
Image used as "original" (resized it to be even more small to reduce the size of base64 output):
encode64:
/9j/4AAQSkZJRgABAQEAYABhAAD/4QBARXhpZgAASUkqAAgAAAABAGmHBAAB
AAAAGgAAAAAAAAACAAKgCQABAAAAZAAAAAOgCQABAAAAfwAAAAAAAAD/2wBD
AAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwc
KDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIy
MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/
/gA0T3B0aW1pemVkIGJ5IEpQRUdtaW5pIDMuMTQuMTQuNzI2NzA4NjAgMHhm
ZjIzZjM3OQD/wAARCAB/AGQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAA
AAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIh
MUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJic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xt7klQVkZl5Htx0opvn2CRxLDL5ShB8ihgB-GKKBH__2Q==

Custom font faces in jsPDF?

Is it possible to include custom fonts in jsPDF ?
With the basic library, if I console log 'doc.getFontList()' I get:
Courier, Helvetica, Times, courier, helvetica, times
But, say I want to use 'Comic Sans' ( not that I would ;o) ) can it be done ?
Even better, could I use a font is locally stored and has been declared in the site with #font-face ?
I found this was possible by modifying jsPDF.js to expose the existing addFont method in the public API.
In jsPDF.js, look for:
//---------------------------------------
// Public API
Add the following:
API.addFont = function(postScriptName, fontName, fontStyle) {
addFont(postScriptName, fontName, fontStyle, 'StandardEncoding');
};
I put this method near other font methods for clarity - API.setFont, API.setFontSize, API.setFontType, etc.
Now in your code, use:
doc.addFont('ComicSansMS', 'Comic Sans', 'normal');
doc.setFont('Comic Sans');
doc.text(50,50,'Hello World');
This works for me with #font-face fonts included with css before loading jsPDF, as well as system fonts. There's probably a better way to do this using jsPDF's plugin framework, but this quick and dirty solution should at least get you going.
Note that doc.getFontList() will not show added fonts:
// TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
It seems to be a lot easier with the latest version of jsPDF (1.5.3):
If you look in the folder jsPDF-master > fontconverter, there's a file fontconverter.html. Open in your browser and use the Browse... button to navigate to, and select your .ttf font file.
Click 'Create'.
The page will offer a "download" to be saved. This will produce a .js file called [something like] RopaSans-Regular-normal.js. This needs to be included in your page producing the PDF's. Personally, I've done it in the main page's header (and please note the order of the scripts):
<!-- pdf creation -->
<script src="FileSaver.js-master/src/FileSaver.js"></script>
<script src="jsPDF-master/dist/jspdf.debug.js"></script>
<!-- custom font definition -->
<script src="path-to-the-file-just-saved/RopaSans-Regular-normal.js" type="module"></script>
Now in your PDF generation method in js:
doc.setFont('RopaSans-Regular');
doc.setFontType('normal');
Here is the solution I'm using...
First, as others have mentioned - you need these two libraries:
jsPDF: https://github.com/MrRio/jsPDF
jsPDF-CustomFonts-support: https://github.com/sphilee/jsPDF-CustomFonts-support
Next - the second library requires that you provide it with at least one custom font in a file named default_vfs.js. I'm using two custom fonts - Arimo-Regular.ttf and Arimo-Bold.ttf - both from Google Fonts. So, my default_vfs.js file looks like this:
(
(function (jsPDFAPI) {
"use strict";
jsPDFAPI.addFileToVFS('Arimo-Regular.ttf','[Base64-encoded string of your font]');
jsPDFAPI.addFileToVFS('Arimo-Bold.ttf','[Base64-encoded string of your font]');
})(jsPDF.API);
Obviously, you version would look different, depending on the font(s) you're using.
There's a bunch of ways to get the Base64-encoded string for your font, but I used this: https://www.giftofspeed.com/base64-encoder/.
It lets you upload a font .ttf file, and it'll give you the Base64 string that you can paste into default_vfs.js.
You can see what the actual file looks like, with my fonts, here: https://cdn.rawgit.com/stuehler/jsPDF-CustomFonts-support/master/dist/default_vfs.js
So, once your fonts are stored in that file, your HTML should look like this:
<script src="js/jspdf.min.js"></script>
<script src="js/jspdf.customfonts.min.js"></script>
<script src="js/default_vfs.js"></script>
Finally, your JavaScript code looks something like this:
const doc = new jsPDF({
unit: 'pt',
orientation: 'p',
lineHeight: 1.2
});
doc.addFont("Arimo-Regular.ttf", "Arimo", "normal");
doc.addFont("Arimo-Bold.ttf", "Arimo", "bold");
doc.setFont("Arimo");
doc.setFontType("normal");
doc.setFontSize(28);
doc.text("Hello, World!", 100, 100);
doc.setFontType("bold");
doc.text("Hello, BOLD World!", 100, 150);
doc.save("customFonts.pdf");
This is probably obvious to most, but in that addFont() method, the three parameters are:
The font's name you used in the addFileToVFS() function in the default_vfs.js file
The font's name you use in the setFont() function in your JavaScript
The font's style you use in the setFontType() function in your JavaScript
You can see this working here: https://codepen.io/stuehler/pen/pZMdKo
Hope this works as well for you as it did for me.
I'm using Angular 8 and Todd's answer worked for me.
Once you get the .js file from fontconverter.html, you can import it in typescript like so:
import fontref = require('path/to/font/CustomFont-normal.js')
Then all you have to do to load the font is 'call' fontref:
makePdf() {
let doc = new jsPDF();
fontref; // 'call' .js to load font
doc.getFontList(); // contains a key-value pair for CustomFont
doc.setFont("CustomFont"); // set font
doc.setFontType("normal");
doc.setFontSize(28);
doc.text("Hello", 20, 20);
window.open(doc.output('bloburl')); // open pdf in new tab
}
After looking at the fontconverter.html, and seeing that it does nothing more than package the TTF files into a base64 string inside a JS file, I came up with the following method that I call before creating my document. It basically does what the individual files resulting from fontconverter.html do, just on-demand:
async function loadFont(src, name, style, weight) {
const fontBytes = await fetch(src).then(res => res.arrayBuffer());
var filename = src.split('\\').pop().split('/').pop();
var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(fontBytes)));
var callAddFont = function () {
this.addFileToVFS(filename, base64String);
this.addFont(filename, name, style, weight );
};
jsPDF.API.events.push(['addFonts', callAddFont]);
}
Call it like this:
await loadFont("/css/fonts/exo-2-v9-latin-ext_latin-italic.ttf", "Exo-2", "italic", 400);
await loadFont("/css/fonts/exo-2-v9-latin-ext_latin-regular.ttf", "Exo-2", "normal", 400);
await loadFont("/css/fonts/exo-2-v9-latin-ext_latin-500.ttf", "Exo-2", "normal", 500);
await loadFont("/css/fonts/exo-2-v9-latin-ext_latin-500italic.ttf", "Exo-2", "italic", 500);
It loads the font from the URL, and adds it to the VFS and font manager. Important: the font name cannot include spaces. You won't get any warnings, but the resulting PDF will either not open or the text will look funny.
Some of these answers are outdated, so I am linking the readme file from Mr. Rio himself regarding the latest release as of this post. Below is a copy of the paragraph from that readme file followed by a link to the readme file itself. Hope this additional resource is helpful:
Use of UTF-8 / TTF:
The 14 standard fonts in PDF are limited to the
ASCII-codepage. If you want to use UTF-8 you have to to integrate a
custom font, which provides the needed glyphs. jsPDF supports
.ttf-files. So if you want to have for example chinese text in your
pdf, your font has to have the necessary chinese glyphs. So check if
your font supports the wanted glyphs or else it will show a blank
space instead of the text.
To add the font to jsPDF use our fontconverter in
/fontconverter/fontconverter.html . The fontconverter will create a
js-file with the content of the provided ttf-file as base64 encoded
string and additional code for jsPDF. You just have to add this
generated js-File to your project. You are then ready to go to use
setFont-method in your code and write your UTF-8 encoded text.
https://github.com/MrRio/jsPDF/blob/master/README.md#use-of-utf-8--ttf
//use necessary config, read the docs http://raw.githack.com/MrRio/jsPDF/master/docs/jsPDF.html
import MuliSemiB64 from "../functions/MuliSemiB64";
let doc = new jsPDF({
orientation: "p",
unit: "px",
format: "a5",
});
doc.addFileToVFS("MULI-SEMIBOLD.TTF", MuliSemiB64());
//MuliSemiB64() is a function that returns the Muli ttf file in its base64 string format, convert your font ttf file and copy the string, save to a variable and use the function to return the string. Use a site like https://www.giftofspeed.com/base64-encoder/ for the conversion
doc.addFont("MULI-SEMIBOLD.TTF", "Muli-Semi-Bold", "Semi-Bold");
doc.setFont("Muli-Semi-Bold", "Semi-Bold");
doc.text("Have Fun :*", 35, 25);
The easiest way that I have found by far is using the jspdf-customfonts package.
Simply install the package by
npm i jspdf-customfonts
then add the following files in the head tag of your index.html for default configurations
script src="https://unpkg.com/jspdf#latest/dist/jspdf.min.js"></script>
<script src="dist/jspdf.customfonts.min.js"></script>
<script src="dist/default_vfs.js"></script>
Now you can download the ttf file of whichever font you want. Then go to this site, select your font and copy the code, and you are done!

How to display Chinese characters with Three.js

I am using the OBJLoader to load a large 3D model (described in a .obj file) and I want to display the models name on its surfaces. Though it seems that Three.js can only display English characters. My question is how can I display Chinese characters in Three.js?
there are a couple of ways to display text (https://github.com/mrdoob/three.js/wiki/Text-in-Three.js), but since exporting a chinese font might be more difficult, it might be easier to draw the chinese characters to a canvas texture and use the texture as a material in the scene.
It seem that you can use Facetype.js to get a Chinese font library, for example"YaHei_Regular.typeface.json" , then you can show Chinese characters.
var fontLoader = new THREE.FontLoader();
fontLoader.load("YaHei_Regular.typeface.json", (font)=> {
this.font = font;
});
Another option is using msdf-bmfont-xml. This example uses Microsoft YaHei.
charset.txt —
你好,世界
You may need to install dependencies first. Then:
npm install msdf-bmfont-xml -g
msdf-bmfont -f json yahei.ttf -i charset.txt --pot --square
and finally, use three-bmfont-text to render the text.
Three.js doesn't display Chinese regularly because it doesn't support the charset. You have to load it dynamically.
It seems there're two methods to load: 1, new THREE.TTFLoader().load('*.ttf') , it loads a ttf file that support Chinese charset. But I failed.
2, new THREE.FontLoader().load('*.json') it loads a json file transformed by
the ttf on http://gero3.github.io/facetype.js/ website.
But firstly you have to find a complete ttf file. I tried 方正兰亭超细黑简体 and 方正赵佶瘦金书 which both work, you can google and download ttf file. I found some ttf can't be identified by three.js completely. You perhaps see some Chinese char display normally but others still display '?'.
The final code snippets as following:
const three_font = new THREE.FontLoader();
three_font.load('*.json', function (font_font) {
font=font_font
})
// finally add text with font
const geometry = new THREE.TextGeometry(
{
font: font,
size, height: h, curveSegments: 4, bevelThickness: 2, bevelSize: 2, bevelEnabled: true
});
geometry.computeBoundingSphere();
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(geometry, pool.textMaterial);
mesh.position.set(x * deviation, y, z * deviation);
mesh.rotation.set(rx, ry, rz);
scene.add(mesh);

Resources