itext实现PDF生成的两种方式-从HTML到PDF

itext实现PDF生成的两种方式-从HTML到PDF

maven依赖pom配置:

<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itext-asian</artifactId>
   <version>5.2.0</version>
</dependency>
<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itextpdf</artifactId>
   <version>5.5.10</version>
</dependency>
<dependency>
   <groupId>com.itextpdf.tool</groupId>
   <artifactId>xmlworker</artifactId>
   <version>5.5.10</version>
</dependency>

 

(一)第一种生成

 

private void doGenerateContractPdf(String contractUrl, String serverRealPath, String pdfFileName) throws Exception {
    com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.LETTER);
    try {
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(serverRealPath + pdfFileName));
        document.open();
        String responseString = HttpUtils.httpPostUrlForPdf(contractUrl);
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(responseString.getBytes()),
                Charset.forName("UTF-8"), new AsianFontProvider());
    } catch (Exception e) {
        logger.error("==========异常==========",e);
        throw e;
    } finally {
        document.close();
    }
}

 

(二)第二种生成 自定义Image类支持BASE64图片生成

 private void doGenerateContractPdfForBase64(String contractUrl, String serverRealPath, String pdfFileName) throws Exception {

com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.LETTER);
    try {
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(serverRealPath + pdfFileName));
        document.open();
        String responseString = HttpUtils.httpPostUrlForPdf(contractUrl);
        InputStream in = new ByteArrayInputStream(responseString.getBytes());

        com.itextpdf.tool.xml.html.TagProcessorFactory tagProcessorFactory = Tags.getHtmlTagProcessorFactory();
        tagProcessorFactory.removeProcessor(HTML.Tag.IMG);
        tagProcessorFactory.addProcessor(new ImageTagProcessor(), HTML.Tag.IMG);

        CssFilesImpl cssFiles = new CssFilesImpl();
        cssFiles.add(XMLWorkerHelper.getInstance().getDefaultCSS());
        StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
        HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl(new AsianFontProvider()));
        hpc.setAcceptUnknown(true).autoBookmark(true).setTagFactory(tagProcessorFactory);
        HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(document, pdfWriter));
        CssResolverPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
        XMLWorker worker = new XMLWorker(pipeline, true);
        Charset charset = Charset.forName("UTF-8");
        XMLParser parser = new XMLParser(true, worker, Charset.forName("UTF-8"));
        if(charset != null) {
            parser.parse(in, charset);
        } else {
            parser.parse(in);
        }
    } catch (Exception e) {
        logger.error("==========异常==========",e);
        throw e;
    } finally {
        document.close();
    }
}

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.codec.Base64;
import com.itextpdf.tool.xml.NoCustomContextException;
import com.itextpdf.tool.xml.Tag;
import com.itextpdf.tool.xml.WorkerContext;
import com.itextpdf.tool.xml.exceptions.RuntimeWorkerException;
import com.itextpdf.tool.xml.html.HTML;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;

/**
 * Created by gaozz on 2017/1/17.
 */
public class ImageTagProcessor extends com.itextpdf.tool.xml.html.Image {

    /*
     * (non-Javadoc)
     *
     * @see com.itextpdf.tool.xml.TagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document)
     */
@Override
public List<Element> end(final WorkerContext ctx, final Tag tag, final List<Element> currentContent) {
        final Map<String, String> attributes = tag.getAttributes();
        String src = attributes.get(HTML.Attribute.SRC);
        List<Element> elements = new ArrayList<Element>(1);
        if (null != src && src.length() > 0) {
            Image img = null;
            if (src.startsWith("data:image/")) {
                final String base64Data = src.substring(src.indexOf(",") + 1);
                try {
                    img = Image.getInstance(Base64.decode(base64Data));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                if (img != null) {
                    try {
                        final HtmlPipelineContext htmlPipelineContext = getHtmlPipelineContext(ctx);
                        elements.add(getCssAppliers().apply(new Chunk((com.itextpdf.text.Image) getCssAppliers().apply(img, tag, htmlPipelineContext), 0, 0, true), tag,
                                htmlPipelineContext));
                    } catch (NoCustomContextException e) {
                        throw new RuntimeWorkerException(e);
                    }
                }
            }

            if (img == null) {
                elements = super.end(ctx, tag, currentContent);
            }
        }
        return elements;
    }
}

字体类:
importcom.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.thinkgem.jeesite.common.config.Global;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AsianFontProvider extends XMLWorkerFontProvider {
    protected Logger logger = LoggerFactory.getLogger(AsianFontProvider.class);
    private static final String contractPdfFontLocation = Global.getConfig("contractPdfFontLocation");

    public Font getFont(final String fontname, final String encoding, final boolean embedded,
            final float size, final int style, final BaseColor color) {
        try {
            FontFactory.register(contractPdfFontLocation + "/simhei.ttf");
            Font font3 = FontFactory.getFont("simhei", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12,style);
            return font3;
        } catch (Exception e) {
            logger.error("==========获取字体出现异常==========",e);
        }
        return null;
    }
}
配置文件:contractPdfFontLocation=D:\\pdffonts
 
PS:
<!-- httpclient -->
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.2</version>
   <exclusions>
      <exclusion>
         <artifactId>commons-logging</artifactId>
         <groupId>commons-logging</groupId>
      </exclusion>
   </exclusions>
</dependency>
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpcore</artifactId>
   <version>4.4.4</version>
</dependency>
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpmime</artifactId>
   <version>4.5.2</version>
</dependency>
 
 
public static String httpPostUrlForPdf(String url) {
    // 设置HTTP请求参数
String result = null;
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    try {
        CloseableHttpResponse response = client.execute(httpGet);
        result = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (ClientProtocolException e) {
        logger.error("http接口调用异常:url is::" + url, e);
        return null;
    } catch (IOException e) {
        logger.error("http接口调用异常:url is::" + url, e);
        return null;
    } finally {
        try {
            client.close();
        } catch (IOException e) {
            logger.error("http接口调用异常:url is::" + url, e);
        }
    }
    return result;
}
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、解决中文问题 2、附字体 3、动态html拼接转pdf public static void htmlCodeComeString(String linkcss,String htmlCode, String outputFile,String title) throws Exception { OutputStream os = new FileOutputStream(outputFile); ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(getConversionHtmlCode(linkcss,htmlCode,title)); ITextFontResolver fontResolver = renderer.getFontResolver(); URL fontPath = ItextUtil.class.getResource("simsun.ttc"); fontResolver.addFont(fontPath.toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 解决图片的相对路径问题 // renderer.getSharedContext().setBaseURL("file:/F:/teste/html/"); renderer.layout(); renderer.createPDF(os); System.out.println("======转换成功!"); os.close(); os.flush(); } public static void main(String[] args) { ItextUtil itextUtil = new ItextUtil(); String html = ""; html += ""; html += "企业信息"; html += " "; html += " "; html += " 登记日期"; html += " 2006-04-28"; html += " "; html += " "; html += " 纳税人编号"; html += " HSJIHKS002"; html += " "; html += " "; html += " 有效标志"; html += " Y"; html += " "; html += " "; html += " 社会信用代码"; html += " 916101317H"; html += " "; html += " "; html += " 评估机关代码"; html += " 盛世"; html += " "; html += " "; html += " 工商注销日期"; html += " 2006-04-28"; html += " "; html += " "; html += ""; String outputFile = "D:\\pdf\\aa.pdf"; try { itextUtil.htmlCodeComeString("",html,outputFile,""); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("生成结束!!!"); }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值