itextpdf使用总结

开始

在近期项目中使用到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)

貌似也就这么多了

第一次写请见谅。

相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页