使用iText将带有图像的HTML转换为PDF

Jdubicki:

我已经搜索了问题,但无法找到针对我特定问题的解决方案。我需要做的是将包含图像和CSS样式的HTML文件转换为PDF。我正在使用iText 5,并且能够将样式包含到生成的PDF中。但是,我仍在努力将图像包括在内。我在下面包含了我的代码。具有绝对路径的图像包含在生成的PDF中,而具有相对路径的图像则不包括在内。我知道我需要实现AbstractImageProvider,但是我不知道该怎么做。任何帮助是极大的赞赏。

Java文件:

public class Converter {

    static String in = "C:/Users/APPS/Desktop/Test_Html/index.htm";
    static String out = "C:/Users/APPS/Desktop/index.pdf";
    static String css = "C:/Users/APPS/Desktop/Test_Html/style.css";

    public static void main(String[] args) {
        try {
            convertHtmlToPdf();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void convertHtmlToPdf() throws DocumentException, IOException {
        Document document = new Document();
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(out));
        document.open();
        XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, new FileInputStream(in), new FileInputStream(css));
        document.close();
        System.out.println("PDF Created!");
    }

    /**
     * Not sure how to implement this
     * @author APPS
     *
     */
    public class myImageProvider extends AbstractImageProvider {

        @Override
        public String getImageRootPath() {
            // TODO Auto-generated method stub
            return null;
        }

    }

}

HTML档案:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>HTML to PDF</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <h1>HTML to PDF</h1>
    <p>
        <span class="itext">itext</span> 5.4.2
        <span class="description"> converting HTML to PDF</span>
    </p>
    <table>
        <tr>
            <th class="label">Title</th>
            <td>iText - Java HTML to PDF</td>
        </tr>
        <tr>
            <th>URL</th>
            <td>http://wwww.someurl.com</td>
        </tr>
    </table>
    <div class="center">
        <h2>Here is an image</h2>
        <div>
            <img src="images/Vader_TFU.jpg" />
        </div>
        <div>
            <img src="https://www.w3schools.com/images/picture.jpg" alt="Mountain" />
        </div>
    </div>
</body>
</html>

CSS文件:

h1 {
    color: #ccc;
}

table tr td {
    text-align: center;
    border: 1px solid gray;
    padding: 4px;
}

table tr th {
    background-color: #84C7FD;
    color: #fff;
    width: 100px;
}

.itext {
    color: #84C7FD;
    font-weight: bold;
}

.description {
    color: gray;
}

.center {
    text-align: center;
}
宏:

以下基于iText5 5.5.12版本

假设您具有以下目录结构:

在此处输入图片说明

使用此代码并使用最新的iText5:

package converthtmltopdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.net.FileRetrieve;
import com.itextpdf.tool.xml.net.FileRetrieveImpl;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.AbstractImageProvider;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import com.itextpdf.tool.xml.pipeline.html.LinkProvider;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 *
 * @author george.mavrommatis
 */
public class ConvertHtmlToPdf {
    public static final String HTML = "C:\\Users\\zzz\\Desktop\\itext\\index.html";
    public static final String DEST = "C:\\Users\\zzz\\Desktop\\itext\\index.pdf";
    public static final String IMG_PATH = "C:\\Users\\zzz\\Desktop\\itext\\";
    public static final String RELATIVE_PATH = "C:\\Users\\zzz\\Desktop\\itext\\";
    public static final String CSS_DIR = "C:\\Users\\zzz\\Desktop\\itext\\";

    /**
     * Creates a PDF with the words "Hello World"
     * @param file
     * @throws IOException
     * @throws DocumentException
     */
    public void createPdf(String file) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        // step 3
        document.open();
        // step 4

        // CSS
        CSSResolver cssResolver =
                XMLWorkerHelper.getInstance().getDefaultCssResolver(false);
        FileRetrieve retrieve = new FileRetrieveImpl(CSS_DIR);
        cssResolver.setFileRetrieve(retrieve);

        // HTML
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
        htmlContext.setImageProvider(new AbstractImageProvider() {
            public String getImageRootPath() {
                return IMG_PATH;
            }
        });
        htmlContext.setLinkProvider(new LinkProvider() {
            public String getLinkRoot() {
                return RELATIVE_PATH;
            }
        });

        // Pipelines
        PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);
        p.parse(new FileInputStream(HTML));

        // step 5
        document.close();
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException, DocumentException {
        // TODO code application logic here
        new ConvertHtmlToPdf().createPdf(DEST);
    }

}

结果如下:

在此处输入图片说明

本示例使用以下代码:https : //developers.itextpdf.com/examples/xml-worker-itext5/xml-worker-examples

希望这可以帮助

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用iText将带有图像和超链接的HTML转换为PDF?

如何在 ServiceNow 中将带有图像的模板 HTML 转换为 PDF?

使用 html2canvas 将带有 highcharts 图形的 html 转换为图像

带有嵌入式SVG的HTML使用飞碟Itext蜡染转换为PDF

Javascript-将带有SVG的HTML div转换为图像

使用iText将HTML转换为PDF

将带有列的 PDF 转换为 rails 中的文本

将带有对象的 JS 数组转换为 HTML 集合

使用Javascript将带有动态变量的对象键值转换为HTML

使用 iText 生成带有页眉和页脚图像的 pdf

itext7 pdf转换为图像

如何使用iText将HTML转换为PDF

使用多种字体将 itext html 转换为 pdf

Google Apps脚本-将带有样式的HTML转换为PDF并附加到电子邮件中-从HTML创建PDF Blob

将带有背景图像的svg rect转换为黑白

如何将带有路线的Google Map转换为javascript中的图像

如何将带有img标签的div转换为图像

需要将带有图像的子目录的目录转换为webp

R语言:将带有规则点的图像转换为数据框

将带有图像上传的 ASP.NET Web 窗体应用程序转换为 Azure

如何将带有西里尔符号的asciidoc转换为pdf?

在Android中使用iText库将图像转换为PDF时,为什么会裁剪图像

将JPG图像转换为PDF而不用使用ghostscript或itext调整图像大小

使用itext将html转换为pdf期间的iText 7异常:无法将UnitValue强制转换为BorderRadius

使用带有 x-emf 图像的 OpenXMLPowerTools 失败将 docx 转换为 html

将带有标头的HTML表转换为Json-Python

在Bash中将带有标头的csv转换为HTML

如何将带有样式的HTML标签转换为打ic?解决问题

pandoc将带有样式表的html转换为docx