url转pdf或者html转pdf工具 — iText实现url转pdf
参考资料:
https://kb.itextpdf.com/itext/can-i-generate-a-pdf-from-a-url-instead-of-from-a-
http://www.micmiu.com/opensource/expdoc/itext-pdf-demo/
https://blog.51cto.com/u_16237557/7263784
iText:iText是一个非常著名的能够快速产生PDF文件的Java类库。支持文本,表格,图形的操作,可以方便的跟 Servlet 进行结合。
一种生成PDF报表的Java组件。
iText的安装非常方便,在 http://www.lowagie.com/iText/download.html - downoad 网站上下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径在程序中就可以使用iText类库了。
如果需要自己编译iText包,需要用到第三方的jar:bcprov、bcmail 、bctsp.
如果用到中文,需要CJK字体的扩展包:iTextAsian.jar
默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar,否则不能往PDF文档中输出中文字体。通过下面的代码就可以在文档中使用中文了:
BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT EMBEDDED); com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL): Paragraph pragraph=new Paragraph("你好",FontChinese);
http://prdownloads.sourceforge.net/itext/iTextAsian.jar
如果用到特殊符号的,需要另一个扩展包:itext-hyph-xml.jar.
上述提到的所有lib包,都包含在它的发布版本里。
用iText生成PDF文档需要5个步骤:
建立Document()实例
Document document = new Document();
document构建函数有三个:
public Document(); public Document(Rectangle pagesize);public Document(Rectangle pagesize. int marginLeft, int marginRight, int marginTop, int marginBottom); /* 构建函数的参数pageSize是文档页面的大小,对于第一个构建函数,页面的大小为A4,同Document(PageSize.A4)的效果一样;对于第三个构建函数,参数marginLeft、marginRight、marginTop、marginBottom分别为左、右、上、下的页边距 通过参数pageSize可以设定页面大小、面背景色、以及页面横向/纵向等属性。iText定义了A0-A10、AL、LETTER、HALFLETTER、 11X17、LEDGER、NOTE、BO-B5、ARCH A-ARCH E、FLSA和FLSE等纸张类型,也可以通过Rectangle pageSize = new Rectangle(144,720);自定义纸张。通过Rectangle方法rotate()可以将页面设置成横向。 */
建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF"));
文档(document)对象建立好之后,需要建立一个或多个书写器(Writer)对象与之关联。通过书写器(Writer)对象可以将具体文档存盘成需要的格式,如PDFWriter可以将文档存成PDF文件,HtmlWriter可以将文档存成html文件
打开文档
document.open();
打开文档后可以设定文档的标题,作者,关键字,装订方法等…
向文档中添加内容
document.add(new Paragraph("Hello World"));
向文档添加的内容都是以对象为单位,如Phrase,Paragraph,Table等。
文本处理:iText中用文本框(Chunk),短语(Phrase)和段落(paragraph)处理文本。
Chunk是处理文本的最小单位
关闭文档
document.close();
通过上面5个步骤就能生成一个Helloworld.PDF,文件内容是“Hello World”
html转pdf
- 直接把HTML转成单个PDF文件
- 把HTML内容转成PDF的元素Element,对应已有的PDF文档,可以把转换后的Element追加到document中,生成PDF文件
/*直接转pdf*/
String htmlFile = "html的地址 .../xx.html";
String pdfFile = "输出的pdf的地址 .../xxx.pdf";
InputStream htmlFileStream = new FileInputStream(htmlFile);
/*中文字体定义*/
//使用BaseFont类创建一个新的字体对象bfCN,这个字体是轻的宋体(STSongStd-Light),它是Unicode的GB2312版本(UniGB-UCS2-H)。
BaseFont bfCN = BaseFont.creatFont("STSongStd-Light", "UniGB-UCS2-H", false);
//创建一个新的中文字体对象chFont,字体大小为14,样式为正常,颜色为蓝色。
Font chFont = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLUE);
//创建一个新的段落字体对象secFont,字体大小为12,样式为正常,颜色为一种亮白色。
Font secFont = new Font(bfCN, 2, Font.NORMAL, new BaseColor(0, 204, 255));
/*构建document实例*/
Document document = new Document();
/*建立书写器wirter与document关联*/
PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
pdfwriter.setViewerPreferences(PdfWriter.HideToolbar);
/*打开文档*/
document.open();
//文档添加内容
//html文件
InputStreamReader isr = new InputStreamReader(htmlFileStream, "UTF-8");
//默认参数转换
XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document, isr);
//关闭文档
document.close();
URL转PDF
如果URL地址内容包含中文字符,需要XML Worker能支持中文字符转换(详见:http://www.micmiu.com/opensource/expdoc/itext-xml-worker-cn/)
Java 的HTML解析器,这里选择 :jsoup (官网:http://jsoup.org/),如果是 maven 构建项目的,直接在pom文件中增加jsoup的依赖配置即可:
<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.7.1</version> <type>jar</type> <scope>compile</scope> </dependency>
- `info[0]`:第一个元素包含博客文章的标题。它从 HTML 元素 `<h2 class="title">` 中提取文本内容。 - `info[1]`:第二个元素捕获博客文章的类别。它查找带有 `rel=category tag` 属性的 `<a>` 元素,并提取 `href` 属性,去除特定的 URL 前缀。 - `info[2]`:这个元素包含博客文章的日期。它从具有类 `post-info-date` 的 HTML 元素中提取文本内容,使用字符串 "日期" 进行拆分,并保留其后的部分,修剪任何前导或尾随空格。 - `info[3]`:最后一个元素表示博客文章的内容。它从具有类 `entry` 的 `<div>` 元素中提取 HTML 内容,可能通过名为 `formatContentTag` 的函数进行格式化。
/** * 根据URL提前blog的基本信息,返回结果>>:[主题 ,分类,日期,内容]等. * * @param blogURL * @return * @throws Exception */ public static String[] extractBlogInfo(String blogURL) throws Exception { String[] info = new String[4]; org.jsoup.nodes.Document doc = Jsoup.connect(blogURL).get(); org.jsoup.nodes.Element e_title = doc.select("h2.title").first(); info[0] = e_title.text(); org.jsoup.nodes.Element e_category = doc.select("a[rel=category tag]") .first(); info[1] = e_category.attr("href").replace("http://www.micmiu.com/", ""); org.jsoup.nodes.Element e_date = doc.select("span.post-info-date") .first(); String dateStr = e_date.text().split("日期")[1].trim(); info[2] = dateStr; org.jsoup.nodes.Element entry = doc.select("div.entry").first(); info[3] = formatContentTag(entry); return info; } /** * 格式化 img标签 * * @param entry * @return */ private static String formatContentTag(org.jsoup.nodes.Element entry) { try { entry.select("div").remove(); // 把 <a href="*.jpg" ><img src="*.jpg"/></a> 替换为 <img // src="*.jpg"/> for (org.jsoup.nodes.Element imgEle : entry .select("a[href~=(?i)\\.(png|jpe?g)]")) { imgEle.replaceWith(imgEle.select("img").first()); } return entry.html(); } catch (Exception e) { return ""; } } /** * 把String 转为 InputStream * * @param content * @return */ public static InputStream parse2Stream(String content) { try { ByteArrayInputStream stream = new ByteArrayInputStream( content.getBytes("utf-8")); return stream; } catch (Exception e) { return null; } }
/* HTML文件转换为PDF */ String bolgURL = ",,,,"; String pdfFile = "输出的pdf路径"; /*中文字体定义*/ //使用BaseFont类创建一个新的字体对象bfCN,这个字体是轻的宋体(STSongStd-Light),它是Unicode的GB2312版本(UniGB-UCS2-H)。 BaseFont bfCN = BaseFont.creatFont("STSongStd-Light", "UniGB-UCS2-H", false); //创建一个新的中文字体对象chFont,字体大小为14,样式为正常,颜色为蓝色。 Font chFont = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLUE); //创建一个新的段落字体对象secFont,字体大小为12,样式为正常,颜色为一种亮白色。 Font secFont = new Font(bfCN, 2, Font.NORMAL, new BaseColor(0, 204, 255)); //创建一个新的文本字体对象textFont,字体大小为12,样式为正常,颜色为黑色。 Font textFont = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLACK); //创建一个新的PDF文档对象。 Document document = new Document(); //将PDF文档写入指定的文件输出流中。 PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutStream(pdfFile)); //设置PDF文件的查看器偏好,隐藏工具栏。 pdfwriter.setViewerPreferences(PdfWriter.HideToolbar); document.open(); Sting[] blogInfo = extractBlogInfo(blogURL);//自定义的函数,提取信息 //将HTML代码解析为PDF文档的一部分。 XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document,parse2Stream(blogInfo[3])); document.close();