itextpdf使用总结_com.itextpdf.text.rectangle-程序员宅基地

技术标签: 个人项目  itext  

开始

在近期项目中使用到itextpdf用于导出pdf,主要是html代码块(这块主要用到freemarker作为传值。下文会用到freemarker如何将数据库html代码块及数据整合成完整html)。

maven引入必须的包

<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			<version>5.2.0</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-pdfa</artifactId>
			<version>5.5.7</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-xtra</artifactId>
			<version>5.5.7</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.5.7</version>
		</dependency>

HtmlUtil.java

package xxx.xxx;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

public class HtmlUtil {

    private static final Logger logger = LoggerFactory.getLogger(HtmlUtil.class);

    private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>";
    private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>";
    private static final String regEx_html = "<[^>]+>";
    private static final String regEx_space = "\\s*|\t|\r|\n";

    public static String delHTMLTag(String htmlStr) {
        Pattern p_script = Pattern.compile("<script[^>]*?>[\\s\\S]*?<\\/script>", 2);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll("");

        Pattern p_style = Pattern.compile("<style[^>]*?>[\\s\\S]*?<\\/style>", 2);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll("");

        Pattern p_html = Pattern.compile("<[^>]+>", 2);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll("");

        Pattern p_space = Pattern.compile("\\s*|\t|\r|\n", 2);
        Matcher m_space = p_space.matcher(htmlStr);
        htmlStr = m_space.replaceAll("");
        return htmlStr.trim();
    }

    public static String getTextFromHtml(String htmlStr) {
        htmlStr = delHTMLTag(htmlStr);
        htmlStr = htmlStr.replaceAll("&nbsp;", "");
        htmlStr = htmlStr.substring(0, htmlStr.indexOf("。") + 1);
        return htmlStr;
    }

    public static String getHtmlFile(String urlStr) {
        try {
            if (urlStr.indexOf("?") != -1) {
                urlStr =
                        urlStr + "&locale=" + LocaleContextHolder.getLocale().toString();
            } else {
                urlStr =
                        urlStr + "?locale=" + LocaleContextHolder.getLocale().toString();
            }
            System.out.println("-------" + urlStr);
            URL url = new URL(urlStr);
            URLConnection uc = url.openConnection();
            InputStream fis = uc.getInputStream();

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int ch;
            while ((ch = fis.read()) != -1) {
                bos.write(ch);
            }
            fis.close();
            byte[] bs = bos.toByteArray();
            bos.close();
            String basil = new String(bs, "UTF-8");
            return basil.toString();
        } catch (IOException e) {
            logger.error("get html error: " + urlStr, e);
            e.printStackTrace();
        }
        return "";
    }

    public static ByteArrayOutputStream parseHTML2PDF(ByteArrayOutputStream pdfOut, String html, Rectangle pageSize)
            throws Exception {
        BaseFont bfCN = BaseFont.createFont("STSong-Light", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        Font chFont = new Font(bfCN, 12.0F, 0, BaseColor.BLUE);
        Font secFont = new Font(bfCN, 12.0F, 0, new BaseColor(0, 204,
                255));

        Document document = new Document(pageSize);

        PdfWriter pdfwriter = PdfWriter.getInstance(document,
                pdfOut);
        pdfwriter.setViewerPreferences(4096);
        document.open();

        logger.debug("转换html为pdf,pageSize:{}, html: {}", pageSize.toString(), html);


        XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document, new StringReader(html));

        document.close();
        return pdfOut;
    }

    public static ByteArrayOutputStream parseHTML2PDFOfFootHeader(ByteArrayOutputStream pdfOut, String html, Rectangle pageSize, String headerStr)
            throws Exception {
        BaseFont bfCN = BaseFont.createFont("STSong-Light", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        Font chFont = new Font(bfCN, 12.0F, 0, BaseColor.BLUE);
        Font secFont = new Font(bfCN, 12.0F, 0, new BaseColor(0, 204,
                255));

        Document document = new Document(pageSize);

        PdfWriter pdfwriter = PdfWriter.getInstance(document,
                pdfOut);
        pdfwriter.setViewerPreferences(4096);

        HeaderFooter header = new HeaderFooter(headerStr, 8, pageSize);

        pdfwriter.setPageEvent(header);
        document.open();

        XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document, new StringReader(html));

        document.close();
        return pdfOut;
    }

    public static ByteArrayOutputStream parseHTML2PDFOfFootHeader(ByteArrayOutputStream pdfOut, String html, Rectangle pageSize, String headerStr, float headx, float heady, float footx, float footy)
            throws Exception {
        BaseFont bfCN = BaseFont.createFont("STSong-Light", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        Font chFont = new Font(bfCN, 12.0F, 0, BaseColor.BLUE);
        Font secFont = new Font(bfCN, 12.0F, 0, new BaseColor(0, 204,
                255));

        Document document = new Document(pageSize);

        PdfWriter pdfwriter = PdfWriter.getInstance(document,
                pdfOut);
        pdfwriter.setViewerPreferences(4096);

        HeaderFooter header = new HeaderFooter(headerStr, 8, pageSize, headx, heady, footx, footy);

        pdfwriter.setPageEvent(header);
        document.open();

        XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document, new StringReader(html));

        document.close();
        return pdfOut;
    }

    public static Map<String, Double> setMapValues(Map<String, Double> map, String key, Double value) {
        if (map.containsKey(key)) {
            value = Double.valueOf(value.doubleValue() + ((Double) map.get(key)).doubleValue());
        }
        map.put(key, value);
        return map;
    }

    public static void main(String[] args) {
        //获取
        String str = "<div style='text-align:center;'> ${phone1}<br/><span style='font-size:14px;'> </span><span style='font-size:18px;'>${phone2}</span><br/></div>";
        Map<String, Object> variables = new HashMap<String, Object>(0);
        variables.put("phone1", "a张1");
        variables.put("phone2", "b李2");
        String html = ElUtils.parseExpression(variables, str, "test");
        System.out.println(html);
        try {
            ByteArrayOutputStream btOutputStream = parseHTML2PDF(new ByteArrayOutputStream(), html, new RectangleReadOnly(842, 1191));
            FileOutputStream fileOutputStream = new FileOutputStream("F:\\baidu.pdf");
            fileOutputStream.write(btOutputStream.toByteArray());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

HeaderFooter.java

package xxx.xxx;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import java.io.IOException;

public class HeaderFooter
  extends PdfPageEventHelper
{
  Font font = new XMLWorkerFontProvider().getFont("宋体", 12.0F, BaseColor.RED);
  PdfTemplate total;
  public String header = "";
  public Rectangle pageSize = PageSize.A4;
  public int presentFontSize = 12;
  public BaseFont bf = null;
  public Font fontDetail = null;
  public float headx = 0.0F;
  public float heady = 0.0F;
  public float footx = 0.0F;
  public float footy = 0.0F;

  public HeaderFooter() {}

  public HeaderFooter(String yeMei, int presentFontSize, Rectangle pageSize)
  {
    this.header = yeMei;
    this.presentFontSize = presentFontSize;
    this.pageSize = pageSize;
  }

  public HeaderFooter(String yeMei, int presentFontSize, Rectangle pageSize, float headx, float heady, float footx, float footy)
  {
    this.header = yeMei;
    this.presentFontSize = presentFontSize;
    this.pageSize = pageSize;
    this.headx = headx;
    this.heady = heady;
    this.footx = footx;
    this.footy = footy;
  }

  public HeaderFooter(String yeMei, int presentFontSize, Rectangle pageSize, float headx, float heady)
  {
    this.header = yeMei;
    this.presentFontSize = presentFontSize;
    this.pageSize = pageSize;
    this.headx = headx;
    this.heady = heady;
  }

  public void setHeader(String header)
  {
    this.header = header;
  }

  public void setPresentFontSize(int presentFontSize)
  {
    this.presentFontSize = presentFontSize;
  }

  public void onOpenDocument(PdfWriter writer, Document document)
  {
    PdfContentByte cb = writer.getDirectContent();
    this.total = cb.createTemplate(30.0F, 16.0F);
  }

  public void onEndPage(PdfWriter writer, Document document)
  {
    try
    {
      if (this.bf == null) {
        this.bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
      }
      if (this.fontDetail == null) {
        this.fontDetail = new Font(this.bf, this.presentFontSize, 0);
      }
    }
    catch (DocumentException e)
    {
      e.printStackTrace();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    int pageS = writer.getPageNumber();
    String foot1 = "第 " + pageS + " 页 /共";
    Phrase footer = new Phrase(foot1, this.fontDetail);

    float len = this.bf.getWidthPoint(foot1, this.presentFontSize);

    ColumnText.showTextAligned(writer.getDirectContent(), 0, new Phrase(this.header, this.fontDetail), document.left() + this.headx, document.top() + 20.0F + this.heady, 0.0F);

    PdfContentByte cb = writer.getDirectContent();

    ColumnText.showTextAligned(cb, 1, footer, (document.rightMargin() + document.right() + document.leftMargin() - document.left() - len) / 2.0F + 20.0F + this.footx, document.bottom() - 20.0F + this.footy, 0.0F);

    cb.addTemplate(this.total, (document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F + 20.0F + this.footx, document.bottom() - 20.0F + this.footy);
  }

  public void onCloseDocument(PdfWriter writer, Document document)
  {
    this.total.beginText();
    this.total.setFontAndSize(this.bf, this.presentFontSize);
    String foot2 = writer.getPageNumber() - 1 + " 页 ";
    this.total.showTextAligned(3, foot2, 2.0F, 0.35F, 0.0F);

    this.total.endText();
    this.total.closePath();
  }
}

util使用方法

package xxx.xxx;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import com.itextpdf.text.PageSize;

public class TestHtml {

	
	public static void main(String[] args) {
		
		String htmlString ="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\n" + 
				"<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n" + 
				"<head>\r\n" + 
				"    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\r\n" + 
				"    <meta http-equiv=\"Content-Style-Type\" content=\"text/css\"/>\r\n" + 
				"    <title></title>\r\n" + 
				"</head>\r\n" + 
				"<body>\r\n" + 
				"<!--第一页开始-->\r\n" + 
				"<div class=\"page\" >\r\n" + 
				"    <div style=\"text-align : center;\"><p>${templateName}</p></div>\r\n" + 
				"    <div><p>iText   guanwang:${ITEXTUrl}</p></div>\r\n" + 
				"    <div><p>FreeMarker   gunawang:${freeMarkerUrl}</p></div>\r\n" + 
				"    <div><p>JFreeChartJiaocheng:${JFreeChartUrl}</p></div>\r\n" + 
				"    <div>liebiaozhi:</div>\r\n" + 
				"</div>\r\n" + 
				"<!--第一页结束-->\r\n" + 
				"<!---分页标记-->\r\n" + 
				"<span style=\"page-break-after:always;\"></span>\r\n" + 
				"<!--第二页开始-->\r\n" + 
				"\r\n" + 
				"\r\n" + 
				"<!--第二页结束-->\r\n" + 
				"</body>\r\n" + 
				"</html>";
		
		  Map<String, Object> variables = new HashMap<String, Object>(0);
	        variables.put("templateName", "1234567");
	        variables.put("ITEXTUrl", "longxing520.cn");
	        variables.put("freeMarkerUrl", "longxing520.cn/aaa");
	        variables.put("JFreeChartUrl", "JFreelongxing520.cn");
	        //此处主要是将html与数据绑定。
	        String html = ElUtils.parseExpression(variables, htmlString, "模板格式错误");
	        System.out.println(html);
	        try {
	            ByteArrayOutputStream btOutputStream = HtmlUtil.parseHTML2PDF(new ByteArrayOutputStream(), html, PageSize.A5);
	            FileOutputStream fileOutputStream = new FileOutputStream("F:\\baidu.pdf");
	            fileOutputStream.write(btOutputStream.toByteArray());

	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	}
}

由于前期用到的是EL表达是将带有el表达式的html代码块及数据转为标准的html代码。后期没用到,暂时就按照这个来吧。如有需要我贴出el表达式工具那块(主要是list时写的工具会后面数据会将前期的数据覆盖。所以后期用到freemarker)

貌似也就这么多了

第一次写请见谅。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u012817163/article/details/107996496

智能推荐

GitHub黑科技,淘宝自动刷喵币!靠这一个脚本就够了-程序员宅基地

文章浏览阅读1.8k次。点击上方“Github爱好者社区”,选择星标回复“资料”,获取小编整理的一份资料开源最前线(ID:OpenSourceTop)猿妹综合整理一年一度的双十一大促又来了,原以为今年总算不需..._github淘宝脚本

C# UI常用操作 - Mars的专栏 - 博客频道 - CSDN.NET http://blog.csdn.net/shuyizhi/article/details/6830405-程序员宅基地

文章浏览阅读354次。using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI

openwrt 串口 开发 注意事项_stty speed 9600 cs8 -cstopb -echo raw-程序员宅基地

文章浏览阅读1.3k次。1. 可以安装 sttyopkg update opkg install coreutils-stty2. 设定串口波特率stty -F /dev/ttyS1 raw speed 9600注意,如果在使用串口时,一定要注意 ttyS0 ttyS1 这个S是大写的,再说一下,是大写的在不清楚是,要常用TAB进行补全,这样就不会出错。_stty speed 9600 cs8 -cstopb -echo raw

卷积神经网络如何提取特征的?-程序员宅基地

文章浏览阅读3.2k次,点赞2次,收藏20次。用文氏图来理解卷积神经网络如何决定提取哪些特征:https://blog.csdn.net/kane7csdn/article/details/84890592为什么卷积能够提取图像的特征?看完此文应该能够给你一个答案:https://blog.csdn.net/charleswangzi/article/details/82733016浅析卷积神经网络为何能够进行特征提取:https://blog.csdn.net/weixin_42078618/article/details/838_卷积神经网络如何提取特征

【NLP】新闻文本分类----基于机器学习的文本分类_新闻文本分类 模型-程序员宅基地

文章浏览阅读1.4k次,点赞3次,收藏22次。【NLP】新闻文本分类----基于机器学习的文本分类机器学习模型文本表示方法one-hotBag of WordsN-gramTF-IDF基于机器学习的文本分类词袋法 + 岭回归分类器`TF-IDF + 岭回归分类器不同参数下的TF-IDF算法TF-IDF参数解读改变不同参数的F1结果改变ngram_range的参数TF-IDF算法与其他分类器模型机器学习模型机器学习是对能通过经验自动改进的计算机算法的研究。机器学习通过历史数据训练出模型对应于人类对经验进行归纳的过程,机器学习利用模型对新数据进行预测对_新闻文本分类 模型

Web API 版本控制的几种方式_web 、app 共用一个后端,版本号如何控制-程序员宅基地

文章浏览阅读3.9w次,点赞10次,收藏28次。http://www.troyhunt.com/2014/02/your-api-versioning-is-wrong-which-is.html这篇文章写得很好,介绍了三种实现web api版本化的三种方式。我从评论里又收集到两种方式,所以一共是5种:方式一:利用URL HTTP GET:https://haveibeenpwned.com/api/v2/breacheda..._web 、app 共用一个后端,版本号如何控制

随便推点

twisted.internet.error.TimeoutError错误的解决方法_twisted.internet.error.tcptimedouterror-程序员宅基地

文章浏览阅读1.6k次。使用scapy 爬取的时候,少数请求链接会出现请求超时,当出现请求超时时,爬虫会自动重试三次。若超过180s且三次后仍没有得到数据,就会放弃请求出现twisted.internet.error.TimeoutError 错误。此时就出现了爬取失败的情况。错误原因:当网络无法满足在180s内下载完所有的请求数量,就会出现此类错误。解决办法:这里做个示例,具体情况具体分析1、降低同时请求的数量CONCURRENT_REQUESTS = 22、 设置合适的超时时间,DOWNLOAD_TIMEOU_twisted.internet.error.tcptimedouterror

[linux]单网卡绑定多个IP_单网卡绑定两个ip-程序员宅基地

文章浏览阅读215次。[linux]单网卡绑定多个IP配置默认网关:默认网关的文件:/etc/sysconfig/network 内容如下:其中test为主机名称NETWORKING=yesHOSTNAME=testGATEWAY=192.168.168.250或:NOZEROCONF=yesGATEWAY=10.230.17.1eth0对应的配置文件/etc/sysconfig/network-scripts/ifcfg-eth0内容如下:DEVICE=eth0BOO.._单网卡绑定两个ip

SwiftUI 5教程之Metal shader 系列资源(WWDC23)_swiftui_metal-程序员宅基地

文章浏览阅读174次。WWDC23为 SwiftUI 引入了许多新功能,特别是这些修改器对金属着色器的支持。_swiftui_metal

Ubuntu18.04 Server配置固定IP 以及Ubuntu19.10 Server配置固定IP_没有 50-cloud-init.yaml文件-程序员宅基地

文章浏览阅读3.1k次。一、Ubuntu18.04 Server1、查看/etc/netplan50-cloud-init.yaml文件及内容,没有文件时创建2、修改文件 ,添加 IP 地址、子网掩码、网关、DNS 服务器等配置。用192.168.1.231作为网卡enp2s0的 IP 地址,192.168.1.1作为网关地址。然后用192.168.1.1作为DNS 服务器 IP。子网掩码不清..._没有 50-cloud-init.yaml文件

linux记录所有用户的操作命令_linux 记录操作命令-程序员宅基地

文章浏览阅读2.9k次,点赞3次,收藏5次。1.在/etc/profile加入如下脚本PS1="`whoami`@`hostname`:"'[$PWD]'historyUSER_IP=`who -u am i 2&gt;/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`if [ "$USER_IP" = "" ]thenUSER_IP=`hostname`fiif [ ! -d ..._linux 记录操作命令

Unit8 数组_uint8数组-程序员宅基地

文章浏览阅读5.2k次。Unit8 数组1. 理解数组2. 一位数组3. 二维数组4. 多维数组 1、认识数组软件的基本功能是处理数据,而在处理数据时,必须先进行数据持有,将数据持有之后,再对数据进行处理。我们将程序中可以临时存储数据的部分叫做容器。在java中,存储数据的容器效率最快的就是数组,也是java最基本的容器。数组,顾名思义就_uint8数组

推荐文章

热门文章

相关标签