1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > itext html转换pdf itext转换html成pdf(支持中文 图片)

itext html转换pdf itext转换html成pdf(支持中文 图片)

时间:2024-06-10 03:53:15

相关推荐

itext html转换pdf itext转换html成pdf(支持中文 图片)

1.首先导入依赖

com.itextpdf

itextpdf

5.5.11

com.itextpdf

itext-asian

5.2.0

org.xhtmlrenderer

flying-saucer-pdf

9.0.7

2.代码部分

package com.pdf.util;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.OutputStream;

import org.jsoup.Jsoup;

import org.xhtmlrenderer.pdf.ITextFontResolver;

import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.pdf.BaseFont;

/**

* 转换html为pdf

* @author Uncle Liu

*

*/

public class Html2pdf {

/**

* 将HTML转成PD格式的文件。html文件的格式比较严格

* @param htmlFile

* @param pdfFile

* @throws Exception

*/

//

public static void html2pdf(String htmlFile, String pdfFile) throws Exception {

// step 1

String url = new File(htmlFile).toURI().toURL().toString();

System.out.println(url);

// step 2

OutputStream os = new FileOutputStream(pdfFile);

ITextRenderer renderer = new ITextRenderer();

renderer.setDocument(url);

// step 3 解决中文支持

ITextFontResolver fontResolver = renderer.getFontResolver();

if("linux".equals(getCurrentOperatingSystem())){

fontResolver.addFont("/usr/share/fonts/chiness/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

}else{

fontResolver.addFont("C:\\Windows\\WinSxS\\amd64_microsoft-windows-font-truetype-simsun_31bf3856ad364e35_10.0.17134.1_none_e089ab61d8d9374e\\simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

}

renderer.layout();

renderer.createPDF(os);

os.close();

System.out.println("create pdf done!!");

}

public static String getCurrentOperatingSystem(){

String os = System.getProperty("os.name").toLowerCase();

System.out.println("---------当前操作系统是-----------" + os);

return os;

}

public static void main(String[] args) {

String htmlFile = "D:\\WorkSpace\\IdeaProjects\\pdf\\src\\main\\resources\\templates\\u.html";

String pdfFile = "c:/test.pdf";

try {

Html2pdf.html2pdf(htmlFile, pdfFile);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

}

}

3.html页面

注意:html格式非常严格,图片地址这里用的是绝对路径(file:///D:/WorkSpace/IdeaProjects/pdf/src/main/resources/static/images/1.jpg)

如果是相对路径要在后台设置

Title

/*没有background-color生产的pdf会是空白*/

body{ text-align:center;border: 0px;margin: 0px;background-color:#FFFFFF;}

.div{ margin:0 auto; width:1188px; height:auto;}

body {

/*中文支持*/

font-family:SimSun;

}

123我

4.生成pdf

超出页面长度时会自动分页

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。