缩小HTML页面并转换为A4尺寸pdf

时间:2013-01-11 12:25:47

标签: java html pdf pdf-writer

将html页面转换为pdf。当我将页面转换为pdf时, html页面内容不适合A4页面。我希望整个html页面转换为pdf而不会丢失任何内容。

我已经拥有将html转换为pdf

的代码
            String tempOutFileNameXHTML = "/Users/Common/index" + i + DOT + "xhtml";
            String tempOutFileNamePDF = "/Users/Common/index" + i + DOT + PDF;
            File targetFile = targetFiles.get(i); // gets all the specified html files
            CleanerProperties props = new CleanerProperties();
            props.setTranslateSpecialEntities(true);
            props.setTransResCharsToNCR(true);
            props.setOmitComments(true);

            //checking of starting and ending tags are in proper
            HtmlCleaner htmlCleaner = new HtmlCleaner(props);
            TagNode tagNode = htmlCleaner.clean(targetFile);
            PrettyXmlSerializer prettyXmlSerializer = new PrettyXmlSerializer(props);

            prettyXmlSerializer.writeToFile(tagNode, tempOutFileNameXHTML, "utf-8");

            File xhtmlpath = new File(tempOutFileNameXHTML);
            File pdfPath = new File(tempOutFileNamePDF);
            com.itextpdf.text.Document pdfDocument = null;
            PdfWriter pdfWriter = null;
            pdfDocument = new com.itextpdf.text.Document(com.itextpdf.text.PageSize.A4); // TODO handle this

            pdfWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(pdfPath));
            pdfDocument.open();
            Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 25, Font.BOLD);
            pdfDocument.add(new Paragraph("Target : " + targetFile.getParentFile().getName(), catFont));

            XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, (com.itextpdf.text.Document) pdfDocument,
                    new FileInputStream(xhtmlpath), null);

            pdfDocument.close();

这里的问题是当html页面宽度太长时,它不适合A4尺寸pdf。无论如何缩小或使其成为pdf而没有任何内容丢失。 ?  我怎样才能做到这一点 ? Html页面可以缩小并转换为pdf?关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:0)

Flying Saucer XHTML渲染器项目支持将XHTML输出为PDF。请查看示例here。”

> SOURCE<

答案 1 :(得分:0)

iText可能支持CSS样式。您可以使用样式表格式化HTML页面,使其适合一个页面。有关样式表和iText的一些信息: http://itextpdf.com/examples/iia.php?id=56

如上所述,您还可以尝试Flying Saucer,它是另一种HTML到PDF转换器。至少使用Flying Saucer,你可以提供真正的样式表,CSS支持非常好。