如何在itextpdf HtmlConverter中设置页面方向

问题描述 投票:0回答:1

在数据库中,我存储了不同的 pdf html 模板。今天客户要求添加横向模板。

好吧,现在转换工作不正确:模板是横向的,并且部分文本在页面之外,因为页面是垂直方向的。

我使用了itextpdf,从html到pdf的转换如下所示:

public static byte[] convertString(String htmlContent, boolean useDefaultStyles) throws IOException {
        log.debug("html {}", htmlContent == null? 0: htmlContent.length());
        byte[] bytes = new byte[0];
        if(Strings.isNullOrEmpty(htmlContent)){
            return bytes;
        }
        try{
            if(useDefaultStyles){
                htmlContent = htmlContent.replace(
                        "<head>",
                        "<head>\n<style type=\"text/css\">@page {\tsize: A4; margin: 0; }</style>"
                );
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            HtmlConverter.convertToPdf(htmlContent, baos);
            bytes = baos.toByteArray();
        } catch(Exception e){
            log.error("Error converting html to pdf", e);
        }
        log.debug("html2pdf {}", bytes.length);
        return bytes;
    }

我需要添加什么来解决这个问题?

提前致谢。

java itext
1个回答
1
投票

您可以尝试以下代码吗? baseUri 基本上是包含图像/CSS 等资源文件的目录的路径。

/**
 * Creates the PDF file.
 *
 * @param baseUri the base URI
 * @param src     the path to the source HTML file
 * @param dest    the path to the resulting PDF
 * @throws IOException signals that an I/O exception has occurred.
 */
public void createPdf(String baseUri, String src, String dest) throws IOException {
    PdfWriter writer = new PdfWriter(dest);
    PdfDocument pdf = new PdfDocument(writer);
    PageSize pageSize = PageSize.A4.rotate();
    pdf.setDefaultPageSize(pageSize);
    ConverterProperties properties = new ConverterProperties();
    properties.setBaseUri(baseUri);

    HtmlConverter.convertToPdf(new FileInputStream(src), pdf, properties);
}
© www.soinside.com 2019 - 2024. All rights reserved.