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

搜索了这些问题,但未能找到解决我具体问题的方法.我需要做的是将包含图像和CSS样式的 HTML文件转换为PDF.我正在使用iText 5,并且能够将样式包含在生成的PDF中.但是,我仍然在努力包括图像.我在下面提供了我的代码.具有绝对路径的图像包含在生成的PDF中,具有相对路径的图像不包括在内.我知道我需要实现Abstract ImageProvider,但我不知道该怎么做.任何帮助是极大的赞赏.

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版本

假设您有这个目录结构:

enter image description here

使用此代码并使用最新的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);
    }

}

这是结果:

enter image description here

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

希望这可以帮助

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些