Я пытаюсь добавить собственный шрифт в jsPDF. Я преобразовал свой файл в base64 и сделал следующее:
doc.addFileToVFS("font/rajdhani-regular-webfont.woff", base64enc);
Где base64enc — это строка в кодировке base 64
Затем добавляю шрифт следующим образом:
doc.addFont('font/rajdhani-regular-webfont.woff', 'rajdhani', 'normal');
doc.setFont('rajdhani');
Однако я продолжаю получать следующую ошибку
[Error] jsPDF PubSub Error – "No unicode cmap for font" – Error: No unicode cmap for font — jspdf.min.js:9068
Error: No unicode cmap for font — jspdf.min.js:9068registerTTF — jspdf.min.js:9068i — jspdf.min.js:9027:86open — jspdf.min.js:9032(anonymous function) — jspdf.min.js:6031publish — jspdf.min.js:308yt — jspdf.min.js:729:166addFont — jspdf.min.js:1286callme — freport.php:500onclick — freport.php:100
publish (jspdf.min.js:29:5989)
yt (jspdf.min.js:29:18435)
addFont (jspdf.min.js:29:33701)
callme (freport.php:500)
onclick (freport.php:100)
Я не знаю, почему это происходит.
3 ответа
Я тоже боролся, но наконец нашел, как это сделать!
Как упоминалось, здесь есть конвертер шрифтов, созданный jsPDF Участники, которых вы можете найти здесь.
Сначала загрузите сюда свой шрифт, а затем введите его название. Он сгенерирует JS-файл, который затем вам нужно будет включить в свой проект. Если хотите, это может быть ваша папка js.
И как только он окажется в вашей папке, добавьте этот тег скрипта в свой index.html (или любой другой html-файл, для которого вам нужен jsPDF).
<script src="./fontName.js"></script>
Теперь, когда у вас есть шрифт, автоматически добавленный в jsPDF Api для вас с этим файлом, вы можете продолжить и удалить две строки ниже из вашего кода .
doc.addFileToVFS("font/rajdhani-regular-webfont.woff", base64enc);
doc.addFont('font/rajdhani-regular-webfont.woff', 'rajdhani', 'normal');
Как только вы это сделаете, просто проверьте файл, который вы загрузили из конвертера, и вы должны увидеть в самом низу название вашего шрифта в втором параметре приведенного ниже кода .
this.addFont('fontFile.woff', 'THIS IS FONT NAME' , '.......');
Скопируйте это имя. Скажем, его «раджани» для этого примера. Таким образом, вы просто помещаете это перед любым текстом, который вы создаете в экземпляре jsPDF (doc).
doc.setFont('rajdhani');
Вы можете просто проверить это ниже
/*
"p" for portrait page orientation
"pt" for points. default is mm
"a4" is page size
*/
var doc = new jsPDF("p","pt","a4");
doc.setFont('rajdhani');
doc.text('This is a test', 20,20);
doc.save('filename.pdf');
Теперь вы должны увидеть PDF-файл с левым 20px верхним полем 20px с надписью «Это тест» с вашим стилем шрифта.
Надеюсь это поможет
3
Tunc Gerdan
27 Авг 2019 в 14:37
Также для пользователей модуля ES6 шаги очень похожи.
Если вы здесь ищете решение для Ionic 4 angular typescript , как и я, ниже представлено решение, которое сработало для меня!
Сначала вам нужно установить пакет через npm, как показано ниже.
npm install jspdf@latest --save
После этого, как упоминалось в моем предыдущем ответе, есть конвертер шрифтов, созданный jsPDF Contributers, который вы можете найти на здесь. Используйте это, чтобы загрузить файл шрифта и включить его в свой проект в удобное для ссылки место внутри файла TS, чтобы он мог находиться, например, в той же папке, что и файл ts.
-fontname-style.js // <<--- Here (This is the file you downloaded from converter)
-custom.page.module.ts
-custom.page.html
-custom.page.scss
-custom.page.spec.ts
-custom.page.ts
Теперь в свой custom.page.ts импортируйте следующее:
import * as jsPDF from 'jspdf';
import './fontname-style.js';
//OPTIONAL (Only import if you want to use autotable)
import 'jspdf-autotable';
import { autoTable as AutoTable } from 'jspdf-autotable';
Как только вы это сделаете, просто проверьте файл, который вы загрузили из конвертера, и вы должны увидеть в самом низу ваше имя шрифта во втором параметре кода ниже.
This.addFont (‘fontFile.ttf’, ‘fontName’, ‘…….’);
Теперь вы можете создать такую функцию внутри custom.page.ts ;
//custom.component.ts or custom.page.ts etc.
exportPDF(){
var doc = new jsPDF("p","pt","a4"); // You can set your own paramaters
doc.setFont('fontName');
doc.text('This is a test', 20,20); // You can set your own margins
return doc.save('filename.pdf');
}
Теперь вы должны увидеть PDF-файл с левым 20px верхним полем 20px с надписью «Это тест» с вашим стилем шрифта
ДОПОЛНИТЕЛЬНЫЙ ПЛАГИН — AutoTable для jsPDF
Если вы хотите использовать плагин autotable для jsPDF, установите следующий пакет из npm.
npm install jspdf-autotable@latest --save
После установки добавьте эти два импорта в свой custom.page.ts .
import 'jspdf-autotable';
import { autoTable as AutoTable } from 'jspdf-autotable';
Вы можете создать данные из столбцов и заголовков, если хотите
И внутри функции exportPDF (), которую мы создали перед добавлением этих строк;
//custom.component.ts or custom.page.ts etc.
exportPDF(){
var doc = new jsPDF("p","pt","a4");
doc.setFont('fontName');
doc.text('This is a test', 20,20); // <-- Remove this line
((doc as any).autoTable as AutoTable)({
head: [['Name', 'Email', 'Country']], // <-- Table headers
body: [ // <-- Table body
['David', 'david@example.com', 'Sweden'],
['Castille', 'castille@example.com', 'Norway'],
// ...
],
styles: { font: "fontName" } /* <-- This is for the font to work in your
table */
});
return doc.save('filename.pdf');
}
Теперь у вас должен получиться pdf с таблицей внутри вашего шрифта
Надеюсь, это кому-то поможет.
0
Tunc Gerdan
27 Авг 2019 в 14:49
Я столкнулся с той же проблемой и выполнил шаги, которые объяснил @TuncGerdan. Мои ошибки были устранены, но в консоли появляется следующее предупреждение.
jspdf.min.js:29 Unable to look up font label for font 'font name', 'normal'. Refer to getFontList() for available fonts.
Когда я получаю список шрифтов с помощью doc.getFontList (), я вижу пользовательский шрифт, который я включил в список.
Может ли кто-нибудь помочь с этим.
0
B0se
20 Сен 2019 в 16:21
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
Вот здест Unicode in PDF, пишут
See Appendix D (page 995) of the PDF specification. There is a limited number of fonts and
character sets pre-defined in a PDF consumer application. To display other characters you
need to embed a font that contains them. It is also preferable to embed only a subset of
the font, including only required characters, in order to reduce file size.
I am also working on displaying Unicode characters in PDF and it is a major hassle.
adobe.com/devnet/pdf/pdf_reference.html
.
Нету в стандартных шрифтах кириллицы.
В jsPDF нет средств внедрения шрифтов.
Например, mPDF (PHP), так и поступает, внедряет подмножество шрифта.
Т. е. «просмоторщик» pdf должен сам содержать/предоставлять юникодные шрифты.
Предположим наш «просмоторщик» такие шрифты даёт.
Добавьте в файл jspdf.js перед строкой 1912 (return API; функция jsPDF) код
var padz =
[
"",
"0",
"00",
"000",
"0000"
];
var pdfEscape16 = function(text, flags)
{
var ar = ["FEFF"];
for(var i = 0, l = text.length, t; i < l; ++i)
{
t = text.charCodeAt(i).toString(16).toUpperCase();
ar.push(padz[4 - t.length], t);
}
return ar.join("");
};
API.text16 = function (text, x, y, flags)
{
/**
* Inserts something like this into PDF
BT
/F1 16 Tf % Font name + size
16 TL % How many units down for next line in multiline text
0 g % color
28.35 813.54 Td % position
(line one) Tj
T* (line two) Tj
T* (line three) Tj
ET
*/
var undef, _first, _second, _third, newtext, str, i;
// Pre-August-2012 the order of arguments was function(x, y, text, flags)
// in effort to make all calls have similar signature like
// function(data, coordinates... , miscellaneous)
// this method had its args flipped.
// code below allows backward compatibility with old arg order.
if (typeof text === 'number') {
_first = y;
_second = text;
_third = x;
text = _first;
x = _second;
y = _third;
}
// If there are any newlines in text, we assume
// the user wanted to print multiple lines, so break the
// text up into an array. If the text is already an array,
// we assume the user knows what they are doing.
if (typeof text === 'string' && text.match(/[nr]/)) {
text = text.split(/rn|r|n/g);
}
if (typeof flags === 'undefined') {
flags = {'noBOM': true, 'autoencode': true};
} else {
if (flags.noBOM === undef) {
flags.noBOM = true;
}
if (flags.autoencode === undef) {
flags.autoencode = true;
}
}
if (typeof text === 'string') {
str = pdfEscape16(text, flags);
} else if (text instanceof Array) { /* Array */
// we don't want to destroy original text array, so cloning it
newtext = text.concat();
// we do array.join('text that must not be PDFescaped")
// thus, pdfEscape each component separately
for (i = newtext.length - 1; i !== -1; i--) {
newtext[i] = pdfEscape16(newtext[i], flags);
}
str = newtext.join("> TjnT* <");
} else {
throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
}
// Using "'" ("go next line and render text" mark) would save space but would complicate our rendering code, templates
// BT .. ET does NOT have default settings for Tf. You must state that explicitely every time for BT .. ET
// if you want text transformation matrix (+ multiline) to work reliably (which reads sizes of things from font declarations)
// Thus, there is NO useful, *reliable* concept of "default" font for a page.
// The fact that "default" (reuse font used before) font worked before in basic cases is an accident
// - readers dealing smartly with brokenness of jsPDF's markup.
out(
'BTn/' +
activeFontKey + ' ' + activeFontSize + ' Tfn' + // font face, style, size
(activeFontSize * lineHeightProportion) + ' TLn' + // line spacing
textColor +
'n' + f2(x * k) + ' ' + f2((pageHeight - y) * k) + ' Tdn<' +
str +
'> TjnET'
);
return this;
};
Добавлять текст через вызов функции text16.