danfickle / openhtmltopdf

An HTML to PDF library for the JVM. Based on Flying Saucer and Apache PDF-BOX 2. With SVG image support. Now also with accessible PDF support (WCAG, Section 508, PDF/UA)!
https://danfickle.github.io/pdf-templates/index.html
Other
1.93k stars 360 forks source link

How do u make CJK work #922

Closed sujitrect closed 1 year ago

sujitrect commented 1 year ago

Hi, I am unable to render PDF from html that has japanese or CJK characters. I just get # characters in the PDF.

I used the exact html as used in https://sandbox.openhtmltopdf.com/?file=cjk.htm but that too didnt work. Can you please let me know what is the code that renders above html?

My code (it's in Scala):

    val document = Jsoup.parse(htmlInputStream, "UTF-8", "")
    document.outputSettings.syntax(Document.OutputSettings.Syntax.xml)
    val pdfOutStream = new ByteArrayOutputStream(100*1024)

    val builder = new PdfRendererBuilder()
    builder
      .useFastMode()
      .testMode(true)
      .withUri("")
      .toStream(pdfOutStream)
      .withW3cDocument(new W3CDom().fromJsoup(document), "")
      .run()

I use jdk11 and openhtmltopdf:1.0.10

mannixsuo commented 1 year ago
     public static void htmlToPdf(String templatePath, Map<String, Object> args, OutputStream os) throws IOException {
        String html = templateToHtml(templatePath, args);
        PdfRendererBuilder builder = new PdfRendererBuilder();
        builder.useFastMode();
        builder.useFont(PING_FANG_FONT, "pingfang", 400, BaseRendererBuilder.FontStyle.NORMAL, true);
        builder.useFont(PING_FANG_BOLD_FONT, "pingfang", 800, BaseRendererBuilder.FontStyle.NORMAL, true);
        builder.useFont(PING_FANG_LIGHT_FONT, "pingfang", 400, BaseRendererBuilder.FontStyle.ITALIC, true);
        builder.withHtmlContent(html, "");
        builder.toStream(os);
        builder.run();
    }

This is my code.

I guess your issue is cause by document.outputSettings.syntax(Document.OutputSettings.Syntax.xml). You should output document as html format.

sujitrect commented 1 year ago

I am closing this issue as above helped me. In addition I browsed many other isssues here that provided a ton of info on the subject.