html代码转化成pdf文件

来源:互联网 发布:淘宝国新西兰能用吗 编辑:程序博客网 时间:2024/06/05 11:27

所需依赖

<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.3.2</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-hyph-xml</artifactId><version>5.1.1</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>com.itextpdf.tool</groupId><artifactId>xmlworker</artifactId><version>5.4.1</version><scope>system</scope><systemPath>${project.basedir}/lib/xmlworker-1.2.1-micmiu.jar</systemPath></dependency>


http://download.csdn.net/detail/qq_18860653/9693066

xmlworker-1.2.1-micmiu.jar的文件建议用本文给的,不然会出现乱码。还有,注意html标签都需要关闭(<a></a>、<br />)

 

java代码

package yyf.utils.office.itext;import java.io.ByteArrayInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.nio.charset.Charset;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.pdf.PdfWriter;import com.itextpdf.tool.xml.XMLWorkerHelper;/** * html代码转化为pdf * @author Yu Yufeng * */public class HTMlToPDF {public static void main(String[] args) throws DocumentException, IOException {// step 1Document document = new Document();// step 2PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("i://a.pdf"));// step 3document.open();// document.// step 4String s = "<h1>测试</h1>";InputStream in = new ByteArrayInputStream(s.getBytes());// in = new FileInputStream("i://a.html");XMLWorkerHelper.getInstance().parseXHtml(writer, document, in, Charset.forName("UTF-8"));// step 5document.close();System.out.println("success");}public static InputStream stringToInputStream(String str) {try {InputStream is = new ByteArrayInputStream(str.getBytes());int byteRead;while ((byteRead = is.read()) != -1) {System.out.print((char) byteRead);}is.close();return is;} catch (Exception e) {return null;}}}



1 0
原创粉丝点击