如何在 iText 7 中将方向设置为横向

Nee*_*arn 6 java itext itext7

我正在使用带有方法 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ula*_*huk 9

请仅使用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);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢, pdfDocument.setDefaultPageSize(PageSize.A4.rotate()) 正是我正在寻找的,因为我只想旋转文档的某些页面 (2认同)

Sai*_*eek 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);
Run Code Online (Sandbox Code Playgroud)

在这里查看更详细的信息。