当我们使用ITextRenderer从百万富翁HTML模板生成PDF时,如何设置PDF页面大小A4? [英] How to set PDF page size A4 when we use ITextRenderer to generate PDF from thymeleaf HTML template?

查看:4421
本文介绍了当我们使用ITextRenderer从百万富翁HTML模板生成PDF时,如何设置PDF页面大小A4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们使用ITextRenderer从百万富翁HTML模板生成PDF时,如何设置PDF页面大小A4?

How to set PDF page size A4 when we use ITextRenderer to generate PDF from thymeleaf HTML template ?

我已生成PDF但页面大小不合适,如何设置页面大小A4 JAVA中的ITextRenderer库

I have generated PDF but page size is not proper, how to set page size A4 ITextRenderer library in JAVA

    ClassLoaderTemplateResolver templateResolver = new 
    ClassLoaderTemplateResolver();
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("HTML5");

    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);

    Context context = new Context();
    context.setVariable("name", "Thomas");

    String html = templateEngine.process("templates/Quote", context);

    OutputStream outputStream = new FileOutputStream("message.pdf");
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocumentFromString(html);
    renderer.layout();
    renderer.createPDF(outputStream,true);
    outputStream.close();


推荐答案

请注意您使用的是 FlyingSaucer ,而非 iText
FlyingSaucer 是一种内部使用的产品(非常旧版本) iText

Please be aware that you are using FlyingSaucer, not iText. FlyingSaucer is a product that internally uses (a very old version of) iText.

你会立即从10多年的错误修正和发展中解脱出来。

You are immediately cutting yourself off from 10+ years of bugfixes and developments.

如果你愿意只需 iText ,解决此问题的最佳方法是使用pdfHTML。

If you are comfortable going for just iText, the best way of solving this issue is with pdfHTML.

这是我们写给iText7核心的附加组件专门设计用于将HTML转换为PDF的库。

It's an add-on we wrote to the iText7 core library that is specifically designed to convert HTML into PDF.

简单示例:

    File src = new File("source_html_file.html");
    File dest = new File("target_pdf_file.pdf");

    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdf, PageSize.A4);
    InputStream stream = new FileInputStream(src);

    ConverterProperties converterProperties = new ConverterProperties();
    FontProvider dfp = new DefaultFontProvider(true, true, true);
    converterProperties.setFontProvider(dfp);

    HtmlConverter.convertToPdf(stream, pdf, converterProperties);

在线查看教程以获取更多信息
https://developers.itextpdf.com/content/itext-7-examples/itext -7-converting-html-pdf

Check out the tutorials online for more information https://developers.itextpdf.com/content/itext-7-examples/itext-7-converting-html-pdf

这篇关于当我们使用ITextRenderer从百万富翁HTML模板生成PDF时,如何设置PDF页面大小A4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆