html代码转化成pdf文件

所需依赖

<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 1
		Document document = new Document();
		// step 2
		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("i://a.pdf"));
		// step 3
		document.open();
		// document.
		// step 4
		String 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 5
		document.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;
		}

	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值