猿问

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

我正在使用带有方法 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);

    }

}


慕标琳琳
浏览 849回答 2
2回答

天涯尽头无女友

请只使用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);

GCT1015

您可以使用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);
随时随地看视频慕课网APP

相关分类

Java
我要回答