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加<body style="font-size:12.0pt; font-family:微軟雅黑">  字體可以換,然後輸出就能顯示中文了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章