iTextRenderer(Flying Saucer) HTML转PDF

 iTextRenderer 在依赖 iText 的基础上,单独实现了HTML渲染PDF,基本上能实现 CSS 2.1的整体性,并且完全符合 W3C 规范。

使用html和css定义样式和呈现的内容。如下流程图:

                  

 

 

中文支持

首先需要添加中文字库,也就是你的页面中用到的所有字体:

ITextFontResolver fontResolver = renderer.getFontResolver();  
        fontResolver.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); 
        fontResolver.addFont("C:/Windows/Fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        fontResolver.addFont("C:/Windows/Fonts/simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

  

注意:页面中字体不能使用中文,需要使用英文名称,而且是大小写敏感的!例如宋体的英文名称是 SimSun(注意不是simsun!,首字母都是大写的)

      错误写法:font-family:宋体 或者  font-family:simsun

      正确写法:font-family:SimSun 或者 font-family:SimHei

如果生成的pdf中文不显示或者乱码,请确认如下信息:

  • 确保页面中所有内容都指定了字体,最好能指定 body {font-family:....},以防止漏网之鱼。

  • 确保上述所有字体均通过addFont加入,字体名称错误或者字体不存在会抛出异常,很方便,但是没导入的字体不会有任何提示。

  • 确保字体名称正确,不使用中文,大小写正确。

  • 确保html标签都正确,简单的方法是所有内容都去掉,随便写几个中文看看能否正常生成,如果可以,在认真检查html标签,否则再次检查上述几条。

还有就是中文换行的问题了,带有中文而且文字较多存在换行情况时,需要给table加入样式:

table-layout:fixed,然后表格中的td使用%还指定td的宽度。

 

加密及权限

加密方法较为简单:

ITextRenderer renderer = new ITextRenderer();  
 renderer.setPDFEncryption(getEncryption());
 
 private PDFEncryption getEncryption()
{
    PDFEncryption encrypt = new PDFEncryption(new String("a").getBytes(), new String("b").getBytes(), PdfWriter.ALLOW_SCREENREADERS);
    return encrypt;
}

需要引入jar包!bcprov-jdk16-145.jar,百度一下很多的。

两个参数:两个都是密码,不同的是第一个密码是浏览密码,输入该密码打开pdf后根据设置的权限进行控制,第二个密码属于所有者密码,使用该密码打开pdf权限不受控制。

多页面生成pdf

其实很简单,第一个页面不变,从第二个起:

    for(int i = 1; i < inputFile.length; i++)
        {
        	renderer.setDocument(new File(root, inputFile[i]));
        	renderer.layout();
        	renderer.writeNextDocument();
        }
        renderer.finishPDF();

  

标签

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link href="****.css" rel="stylesheet" type="text/css" />
 <bookmarks>  
     <bookmark name="a" href="#a" /> 
      <bookmark name="b" href="#b" /> 
 </bookmarks>  
</head>

注意,如果你是将多个页面生成到一个pdf中,那么只要在最后一个页面中加入bookmark就可以了!否则会重复。

 

页面生成横向的pdf

在html的style里面加入pdf能识别的样式,@page{}这个就是与其他样式区别开来的标志,例如这里面写@page{size:297mm 210mm;}这个就表示纸张的宽是297毫米,高是210毫米,这样打印出来的效果就跟横着的A4纸一样了,一般放在style第一行。

 

页面其他特性

所有style存放在css文件中(如果只是某个特性可以直接写在html),使用link元素关联,media="print"必须被设置。header和footer两个div也是重要的,footer有两个特殊的元素:pagenumber  、 pagecount,设置pdf页数时被使用。

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Alice's Adventures in Wonderland -- Chapter I</title>
        <link rel="stylesheet" type="text/css" href="alice.css" media="print"/>
    </head>
   
    <body>
        <div id="header" style="">Alice's Adventures in Wonderland</div>
        <div id="footer" style="">  Page <span id="pagenumber"/> of <span id="pagecount"/> </div>
               
        <h1>CHAPTER I</h1>
       
        <h2>Down the Rabbit-Hole</h2>
       
        <p class="dropcap-holder">
            <div class="dropcap">A</div>
            lice was beginning to get very tired of sitting by her sister
            on the bank, and of having nothing to do: once or twice she had
            peeped into the book her sister was reading, but it had no pictures
            or conversations in it, `and what is the use of a book,' thought
            Alice `without pictures or conversation?'
        </p>
       
        <p>So she was considering in her own mind (as well as she could,
            for the hot day made her feel very sleepy and stupid), whether the
            pleasure of making a daisy-chain would be worth the trouble of
            getting up and picking the daisies, when suddenly a White Rabbit
        with pink eyes ran close by her. </p>
       
        <p class="figure">
            <img src="alice2.gif" width="200px" height="300px"/>
            <br/>
            <b>White Rabbit checking watch</b>
        </p>
        ... the rest of the chapter
@page {
size: 4.18in 6.88in;
margin: 0.25in;
-fs-flow-top: "header";
-fs-flow-bottom: "footer";
-fs-flow-left: "left";
-fs-flow-right: "right";
border: thin solid black;
padding: 1em;
}
#header {
font: bold serif;
position: absolute; top: 0; left: 0;
-fs-move-to-flow: "header";
}
#footer {
font-size: 90%; font-style: italic;
position: absolute; top: 0; left: 0;
-fs-move-to-flow: "footer";
}
#pagenumber:before {
content: counter(page);
}
#pagecount:before {content: counter(pages); 
}

  

转载于:https://www.cnblogs.com/reese-blogs/p/5546806.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flying Saucer是一个Java库,可以将HTML文档换为PDF格式。它是基于开源的HTML和CSS渲染引擎——WebKit的一个分支。 要使用Flying SaucerHTML换为PDF,您可以按照以下步骤进行操作: 1. 首先,将Flying Saucer添加到您的Java项目中。您可以通过Maven或手动下载JAR文件来完成。Flying Saucer的最新版本可以在其官方网站上找到。 2. 创建一个Java类,并导入所需的Flying Saucer类。 3. 在代码中,使用Flying Saucer提供的API加载和渲染HTML文档。您可以使用`ITextRenderer`类来执行此操作。 4. 设置输出路径和文件名,然后使用`ITextRenderer`类将渲染的内容保存为PDF文件。 下面是一个简单的示例代码,演示了如何使用Flying SaucerHTML换为PDF: ```java import org.xhtmlrenderer.pdf.ITextRenderer; public class HtmlToPdfConverter { public static void main(String[] args) { String inputHtmlPath = "path/to/input.html"; String outputPdfPath = "path/to/output.pdf"; try { // Create an instance of ITextRenderer ITextRenderer renderer = new ITextRenderer(); // Set the input HTML document renderer.setDocument(new File(inputHtmlPath)); // Render the HTML document to PDF renderer.layout(); // Save the rendered PDF to the output path OutputStream outputStream = new FileOutputStream(outputPdfPath); renderer.createPDF(outputStream); outputStream.close(); System.out.println("PDF conversion completed successfully."); } catch (Exception e) { e.printStackTrace(); } } } ``` 您需要将`inputHtmlPath`替换为实际的HTML文件路径,并将`outputPdfPath`替换为要保存的PDF文件路径。 请注意,Flying Saucer对CSS的支持相对较好,但不是完全完善的。因此,在将HTML换为PDF之前,最好确保您的HTML文档与Flying Saucer兼容,并且在渲染过程中没有任何问题。 希望这能帮助到您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值