IText实现Html转PDF itextpdf-5.5.5.jar

环境:itextpdf-5.5.5.jar   xmlworker-5.5.5.jar

尝试做个csdn博文下载器,首要解决的任务是html转pdf,百度到IText,查了很多教程Itext版本都比较老,我下的5.5.5的。


代码不复杂,

	public static void main(String[] args) throws FileNotFoundException,
			Exception {
		String htmlFile = "C:\\Users\\Administrator\\Desktop\\test.htm";

		String pdfFile = "C:\\Users\\Administrator\\Desktop\\test.pdf";
		// PdfUtils.parseHTML2PDFFile(pdfFile, new FileInputStream(htmlFile));
		String ss = "";
		BufferedReader br = new BufferedReader(new InputStreamReader(
				new FileInputStream(htmlFile), "UTF-8"));
		String t = "";
		while ((t = br.readLine()) != null) {
			// System.out.println(t);
			ss += t;
		}
		PdfUtils.parseHTML2PDFFile2(pdfFile, ss);
	}

	public static void parseHTML2PDFFile2(String pdfFile, String html)
			throws DocumentException, IOException {
		Document document = new Document();
		PdfWriter writer = PdfWriter.getInstance(document,
				new FileOutputStream(pdfFile));
		document.open();
		XMLWorkerHelper.getInstance().parseXHtml(writer, document,
				new ByteArrayInputStream(html.getBytes("Utf-8")),
				Charset.forName("UTF-8"));
		document.close();
	}

遇到的问题:中文显示不了,百度了好久没解决,后来尝试写了一个简单的html页面,能显示中文,查了下原因, html要设置字体,在body加  字体可以换,然后输出就能显示中文了。

你可能感兴趣的:(java学习)