java使用itext实现html转pdf

1、引入jar包


  com.lowagie
  itext
  4.2.2
  pom

 

2、ItextUtil示例代码

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.html.simpleparser.StyleSheet;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.List;

public class ItextUtil{
    /**
     * 将html文件打印成pdf文件
     * @param filePath
     * @param pdfPath
     */
    public void htmlCodeToPdf(String filePath, String pdfPath) {
        Document document = new Document();
        try {
            StyleSheet st = new StyleSheet();
            st.loadTagStyle("body", "leading", "16,0");
            PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
            document.open();
            List p = HTMLWorker.parseToList(new FileReader(filePath), st);
            for(int k = 0; k < p.size(); ++k) {
                document.add((Element)p.get(k));
            }
            document.close();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}

3、这份代码实际项目中未采用,可参考另外两篇html转pdf方法

https://blog.csdn.net/wzh474420999/article/details/78533966

https://blog.csdn.net/wzh474420999/article/details/78548891

 

你可能感兴趣的:(java开发,java,html转pdf)