【问题标题】:How to set orientation to Landscape in iText 7如何在 iText 7 中将方向设置为横向
【发布时间】:2019-06-18 05:26:42
【问题描述】:

我正在使用带有方法 convertToPdf() 的 iText7 将 html 转换为 pdf。 PDF 正在正确生成,但横向模式不起作用。

有人能告诉我如何获得横向模式吗?

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.styledxmlparser.css.media.MediaDeviceDescription;
import com.itextpdf.styledxmlparser.css.media.MediaType;

import java.io.File;
import java.io.IOException;

import static com.itextpdf.html2pdf.css.CssConstants.LANDSCAPE;

public class htmlToPDF {

    public static void main(String args[]) throws IOException {

        ConverterProperties properties = new ConverterProperties();

        MediaDeviceDescription med = new MediaDeviceDescription(MediaType.ALL);
        med.setOrientation(LANDSCAPE);
        properties.setMediaDeviceDescription(med);

        HtmlConverter.convertToPdf(new File("D:\\test.html"), new File("D:\\test.pdf"),properties);
    }
}

【问题讨论】:

    标签: java itext itext7


    【解决方案1】:

    请使用以PdfDocument 为参数的转换器方法。比如下一个:convertToPdf(InputStream htmlStream, PdfDocument pdfDocument, ConverterProperties converterProperties)

    现在您唯一需要做的就是在转换 html 文件之前将页面大小设置为文档。

        PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new File(sourcePath)));
        pdfDocument.setDefaultPageSize(PageSize.A4.rotate());
        HtmlConverter.convertToPdf(new FileInputStream(destPath), pdfDocument, props);
    

    【讨论】:

    • 谢谢,pdfDocument.setDefaultPageSize(PageSize.A4.rotate()) 正是我想要的,因为我只想旋转文档的某些页面
    【解决方案2】:

    您可以使用PageOrientationsEventHandler 来处理文档中的方向,例如 -

    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
    PageOrientationsEventHandler eventHandler = new PageOrientationsEventHandler();
    pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, eventHandler);
    Document doc = new Document(pdfDoc);
    doc.add(new Paragraph("A simple page in portrait orientation"));
    eventHandler.setOrientation(LANDSCAPE);
    

    更详细地检查它here

    【讨论】:

    • 但是如何将 html 文件作为输入传递?我正在将 html 文件转换为 pdf。
    • 如果有人希望他的文档具有不同方向的页面,这是一个很好的建议。但是,如果只想在整个文档上设置某些方向,则无需处理 START_PAGE 事件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2017-02-11
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多