1. 程式人生 > >html匯出pdf

html匯出pdf

<!-- html轉PDF -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>kernel</artifactId>
        <version>7.1.1</version>
    </dependency>
    
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>layout</artifactId>
        <version>7.1.1</version>
    </dependency>
    
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>html2pdf</artifactId>
        <version>2.0.1</version>
    </dependency>


public class ItextPDFUtil {

public static void main(String[] args) {
String htmlStr = null;
InputStream inputStream = null;
PdfDocument pd = null;
try {
// 讀取html的流
inputStream = new FileInputStream(new File("F:/協議.html"));

// 流轉換成字串
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = inputStream.read(b)) != -1;) {
out.append(new String(b, 0, n));
}

htmlStr = out.toString();
String pdffile = "F:/test.pdf";

pd = new PdfDocument(new PdfWriter(new FileOutputStream(new File(pdffile))));
// 設定檔案標題為fileName,web上展示的標題為此標題
pd.getDocumentInfo().setTitle(pdffile);
}
catch (Exception e) {
e.printStackTrace();
}

Document document = new Document(pd, PageSize.A4);
try {
// 匯入字型
FontProvider font = new FontProvider();
font.addFont("F:/SimSun.ttf");

ConverterProperties c = new ConverterProperties();
c.setFontProvider(font);
c.setCharset("utf-8");

// 設定頁面邊距 必須先設定邊距,再新增內容,否則頁邊距無效
document.setMargins(50, 0, 50, 0);
List<IElement> list = HtmlConverter.convertToElements(htmlStr, c);
for (IElement ie : list) {
document.add((IBlockElement) ie);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
document.close();
}

}

public static void htmlToPdf(String html, OutputStream outStream, String fontPath) {
PdfDocument pd = null;
Document document = null;
try {
pd = new PdfDocument(new PdfWriter(outStream));

// 匯入字型
FontProvider font = new FontProvider();
font.addStandardPdfFonts();
font.addFont(fontPath);
ConverterProperties c = new ConverterProperties();
c.setFontProvider(font);
c.setCharset("utf-8");

// 設定頁面邊距 必須先設定邊距,再新增內容,否則頁邊距無效
document = new Document(pd, PageSize.A4, true);
document.setMargins(50, 0, 40, 0);
List<IElement> list = HtmlConverter.convertToElements(html, c);
for (IElement ie : list) {
document.add((IBlockElement) ie);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
document.close();
}

}