itextpdf转换html为pdf

pom.xml中引入包
<!-- pdf  -->
<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.5.13</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<!-- 转换html为标准xhtml包-->
<dependency>
    <groupId>net.sf.jtidy</groupId>
    <artifactId>jtidy</artifactId>
    <version>r938</version>
</dependency>
转换pdf工具类
package com.jyd.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.tidy.Tidy;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.UUID;

/**
 * Created by limingliang on 17:45 2018/7/4
 */
public class PdfUtils {

    private static final Logger logger = LoggerFactory.getLogger(PdfUtils.class);
    private static String path = "E:\\IdeaProjects\\temp\\pdf"; // 生成PDF后的存放路径

    /*把html文件转换为pdf文件输出流*/
    public static byte[] convertHtmlToPdf(byte[] html) throws IOException, DocumentException {
        String pdfName = UUID.randomUUID()+".pdf";
        String pdfPath = path+pdfName;
        convertHtmlToPdf(html,pdfPath);

        File file = new File(pdfPath);
        InputStream inputStream = new FileInputStream(file);
        byte[] buffer = getByteByInputStream(inputStream);
        inputStream.close();
        file.delete();

        return buffer;
    }

    /*把html文件转换为pdf文件*/
    public static void convertHtmlToPdf(byte[] html,String pdfPath) throws IOException, DocumentException {
        logger.info("源html文件传入字节流!");
        OutputStream outputStream = new FileOutputStream(pdfPath);
        Rectangle rectPageSize = new Rectangle(PageSize.A4);// A4纸张
        Document document = new Document(rectPageSize, 40, 40, 40, 40);// 上、下、左、右间距
        PdfWriter pdfWriter = PdfWriter.getInstance(document,outputStream);
        document.open();
        ByteArrayInputStream bin = new ByteArrayInputStream(htmlFormat(html));
        logger.info("源html文件读取为缓冲字节流!");
        XMLWorkerHelper wh = XMLWorkerHelper.getInstance();
        wh.parseXHtml(pdfWriter, document, bin, null,Charset.forName("UTF-8"), new ChinaFontProvide());

        logger.info("源html文件转换为pdf文件!");
        document.close();
    }

    /*把html文件转换为pdf文件*/
    public static void convertHtmlToPdf(String htmlPath,String pdfPath) throws IOException, DocumentException {

        InputStream htmlFileStream = new FileInputStream(htmlPath);
        byte[] buffer = getByteByInputStream(htmlFileStream);

        ByteArrayInputStream bin = new ByteArrayInputStream(htmlFormat(buffer));
        // 创建一个document对象实例
        Document document = new Document();
        // 为该Document创建一个Writer实例
        PdfWriter pdfwriter = PdfWriter.getInstance(document,new FileOutputStream(pdfPath));
        pdfwriter.setViewerPreferences(PdfWriter.HideToolbar);
        // 打开当前的document
        document.open();
        XMLWorkerHelper wh = XMLWorkerHelper.getInstance();
        wh.parseXHtml(pdfwriter, document,bin,null,Charset.forName("UTF-8"),new ChinaFontProvide());
        htmlFileStream.close();
        document.close();
    }

    /*创建pdf 返回pdf全路径*/
    public static String createPdf(String pdfPath) throws DocumentException, IOException {

        // 生成pdf 文件
        String pdfName = UUID.randomUUID()+".pdf";
        File outPdf = new File(pdfPath,pdfName);
        OutputStream file = new FileOutputStream(outPdf);

        // 创建pdf Document
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, file);

        //打开Document写入内容
        document.open();
        document.add(new Paragraph("Hello World, iText"));
        document.add(new Paragraph(new Date().toString()));
        document.close();
        file.close();

        // 返回生成的pdf路径
        return outPdf.getPath();
    }

    /*将不标准html转换为标准xhtml格式*/
    public static byte[] htmlFormat(byte[] html) throws FileNotFoundException{
      //输出为xhtml
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 实例化Tidy对象
        Tidy tidy = new Tidy();
        // 设置输入
        tidy.setInputEncoding("UTF-8");
        // 如果是true 不输出注释,警告和错误信息
        tidy.setQuiet(true);
        // 设置输出
        tidy.setOutputEncoding("UTF-8");
        // 不显示警告信息
        tidy.setShowWarnings(false);
        // 缩进适当的标签内容。
        tidy.setIndentContent(true);
        // 内容缩进
        tidy.setSmartIndent(true);
        tidy.setIndentAttributes(false);
        // 只输出body内部的内容
//        tidy.setPrintBodyOnly(true);
        // 多长换行
        tidy.setWraplen(1024);
        // 输出为xhtml
        tidy.setXHTML(true);
        // 去掉没用的标签
        tidy.setMakeClean(true);
        // 清洗word2000的内容
        tidy.setWord2000(true);
        // 设置错误输出信息
        tidy.setErrout(new PrintWriter(System.out));
        tidy.parseDOM(new ByteArrayInputStream(html), baos);
        return baos.toByteArray();
    }

    /*输入流中获取字节数组 */
    public static byte[] getByteByInputStream(InputStream inputStream) throws IOException {

        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        byte[] b = new byte[1024];
        int n;
        //每次从fis读1024个长度到b中,fis中读完就会返回-1
        while ((n = inputStream.read(b)) != -1)
        {
            bos.write(b, 0, n);
        }
        bos.close();
        return bos.toByteArray();
    }

    /** 解决中文字体   */
    public static final class ChinaFontProvide implements FontProvider {

        @Override
        public Font getFont(String arg0, String arg1, boolean arg2, float arg3, int arg4, BaseColor arg5) {
            BaseFont bfChinese = null;
            try {
                bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Font FontChinese = new Font(bfChinese, arg3, arg4);
            return FontChinese;
        }
        @Override
        public boolean isRegistered(String arg0) {
            return false;
        }
    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iText 7 是一个功能强大的 PDF 库,它可以用来创建、修改和转换 PDF 文件。iText 7 还提供了将 PDF 文件转换HTML 的功能。 以下是将 PDF 文件转换HTML 的步骤: 1. 创建一个 PdfDocument 对象,打开需要转换PDF 文件。 ```java PdfDocument pdfDoc = new PdfDocument(new PdfReader("input.pdf")); ``` 2. 创建一个 ConverterProperties 对象,设置转换属性。 ```java ConverterProperties props = new ConverterProperties(); props.setBaseUri("file:///"); ``` 3. 创建一个 ByteArrayOutputStream 对象,用于将 HTML 内容写入。 ```java ByteArrayOutputStream baos = new ByteArrayOutputStream(); ``` 4. 使用 HtmlConverter 类将 PDF 文件转换HTML。 ```java HtmlConverter.convertToHtml(pdfDoc, baos, props); ``` 5. 将 HTML 内容从 ByteArrayOutputStream 对象中读取出来。 ```java String html = new String(baos.toByteArray()); ``` 完整的代码示例: ```java import com.itextpdf.html2pdf.ConverterProperties; import com.itextpdf.html2pdf.HtmlConverter; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfReader; import java.io.ByteArrayOutputStream; import java.io.IOException; public class PdfToHtml { public static void main(String[] args) throws IOException { PdfDocument pdfDoc = new PdfDocument(new PdfReader("input.pdf")); ConverterProperties props = new ConverterProperties(); props.setBaseUri("file:///"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); HtmlConverter.convertToHtml(pdfDoc, baos, props); String html = new String(baos.toByteArray()); System.out.println(html); pdfDoc.close(); } } ``` 请注意,iText 7 中的 HTML 转换器不是完美的,并且可能会出现一些格式问题。如果您需要更高质量的转换,可以尝试其他 PDF HTML 工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值