用阿拉伯字体生成PDF

IT技术 reactjs pdf utf-8 arabic jspdf
2021-05-23 03:53:06

我想在 react 中下载带有阿拉伯字体的 pdf 文件,但没有找到任何解决方案。我目前正在使用 jsPdf 但它没有正确呈现阿拉伯字体

let doc = new PDFDocument
let doc = new pdf();
doc.setFontSize(10);
doc.rect(20, 20, doc.internal.pageSize.getWidth() - 40, 
doc.internal.pageSize.getHeight() - 40, 'S');
doc.setTextColor(128,0,128);
doc.text("Date", 30, 25);
doc.text(this.state.date, 50, 25);
doc.text("السلام عليكم", 30, 35);
doc.text("Quantity", 120, 35);
let distance = 30;
doc.save("data.pdf");

提前致谢

3个回答

首先下载所需的字体。然后去https://rawgit.com/MrRio/jsPDF/master/fontconverter/fontconverter.html

并转换和下载文件。将其移动到您的项目目录并将其导入所需的module中。

您也可以将大字符串放入变量中 const myFont = "VVV....VVV"

然后像这样使用它。

   doc.addFileToVFS("MyFont.ttf", myFont);
   doc.addFont("MyFont.ttf", "MyFont", "normal");
   doc.setFont("MyFont");

现在您需要右对齐文本。

doc.text("Arabic Text", 200, 20, "right");
//OR
doc.text("Arabic Text", 200, 20, { align : "right" } ); 
/* 
200 is the x coordinate and marks the starting position of the text from right.
y coordinate is the distance from the top of the page.
*/

您是否尝试添加 {lang: 'value'} 选项?

doc.text(['لا إله إلا الله محمد رسول الله', 'لا إله إلا الله', 'a'], 100, 100, { lang: 'ar' });

可以按照以下步骤将阿拉伯字体打印为 pdf

  1. 使用html2canvas将 HTML 转换为画布
  2. 使用jspdf将图像转换为pdf

    const input = document.getElementById('divIdToPrint');    
    html2canvas(input)
          .then((canvas) => {
            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF();
            pdf.addImage(imgData, 'PNG', 0, 0);
            pdf.save("download.pdf");  
      });
    

博客中的详细信息

Stackblitz 上的演示链接