将HTML文件转换为PDF文件(Thymeleaf模板转换,简单解决中文问题, 解决HTML带图片转换PDF文件问题)

将HTML文件转换为PDF文件

一、导入依赖



	com.itextpdf
	itextpdf
	5.5.10


	com.itextpdf.tool
	xmlworker
	5.5.8

二、编写HTML文件

注意:HTML文件内不能有为闭合的端口,比如要将标签改为格式




    
    Title


    

Hello Word!

Hello Word!

Hello Word!

Hello Word!

Hello Word!
Hello Word!
Hello Word!

三、编写controller类

package com.cn.controller;


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static org.apache.tomcat.util.file.ConfigFileLoader.getInputStream;


@Controller
public class TestController {

    @GetMapping("/TestPDF")
    @ResponseBody
    public String TestPDF2() throws Exception{
        //第一步,创建一个 iTextSharp.text.Document对象的实例:
        Document document = new Document();
        //第二步,为该Document创建一个Writer实例:
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\HelloWorld2.pdf"));
        //第三步,打开当前Document
        document.open();
        //第四步,为当前Document添加内容:
        //document.add(new Paragraph("Hello World"));
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, 
        new FileInputStream(
        "D:\\Java_IDEA\\Test\\Test-PDF\\src\\main\\resources\\templates\\HelloWorld.html"
        ));
        //第五步,关闭Document
        document.close();
        return "ok";
    }

}

将Thymeleaf模板的HTML文件转PDF

一、导入依赖



	org.springframework.boot
	spring-boot-starter-thymeleaf



	com.itextpdf
	itextpdf
	5.5.10


	com.itextpdf.tool
	xmlworker
	5.5.8

二、完成框架的基本配置

如:pojo,dao,service,serviceimpl等文件

三、写入Controller

package com.cn.controller;

import com.cn.pojo.Dict;
import com.cn.service.DictService;
import com.sun.deploy.net.HttpDownload;
import com.sun.org.apache.xerces.internal.util.HTTPInputSource;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpInputMessage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Controller
public class DictController {
    @Autowired
    private DictService dictService;

	//查询所有的内容
    @RequestMapping("/doFindAll")
    public String doFindAll(Model model){
    	//通过List存储
        List list = dictService.findAll();
        //将list导入到HTML文件内
        model.addAttribute("list",list);
        //跳转到指定HTML页面
        return "Dict";
    }

	//获取HTML的IO输入流
    public InputStream getInputStreamByUrl(String strUrl){
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(),output);
            return  new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try{
                if (conn != null) {
                    conn.disconnect();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
	//存储PDF文件
    @RequestMapping("/doDaYing")
    @ResponseBody
    public String doDaYing(){
        //创建一个 iTextSharp.text.Document对象的实例:
        Document document = new Document();
        try {
            //为该Document创建一个Writer实例:
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\Dict.pdf"));
            //打开当前Document
            document.open();
            //为当前Document添加内容:
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, getInputStreamByUrl("Http://localhost:86/doFindAll"));
        }catch (Exception e){
            e.printStackTrace();
        }
        //关闭Document
        document.close();
        return "OK";
    }
}

简单解决HTML的转换中文问题

1.需要将***改为***

2.需要在******标签出添加style="font-family: SimSun"属性

例如:




    
    Title


    

Hello Word!

Hello Word!

Hello Word!

你好

你好
你好
你好

解决HTML带图片转换PDF文件问题

这里写一个小的测试类,以相对地址测试

一、导入依赖



    org.xhtmlrenderer
    core-renderer
    R8



	com.itextpdf
	itextpdf
	5.5.10


	com.itextpdf.tool
	xmlworker
	5.5.8

二、将图片转入resources文件下保持

目前只测试过JPG,PNG格式的图片,其他暂时没有测试

三、编写图片处理类

package com.cn.uitl;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.codec.Base64;
import org.w3c.dom.Element;
import org.xhtmlrenderer.extend.FSImage;
import org.xhtmlrenderer.extend.ReplacedElement;
import org.xhtmlrenderer.extend.ReplacedElementFactory;
import org.xhtmlrenderer.extend.UserAgentCallback;
import org.xhtmlrenderer.layout.LayoutContext;
import org.xhtmlrenderer.pdf.ITextFSImage;
import org.xhtmlrenderer.pdf.ITextImageElement;
import org.xhtmlrenderer.render.BlockBox;
import org.xhtmlrenderer.simple.extend.FormSubmissionListener;
import java.io.IOException;


/**转换PDF的图片处理*/
public class ImgInputStream implements ReplacedElementFactory{

    /**图片转换base64支持,把图片转换为itext自己的图片对象*/
    public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac,int cssWidth, int cssHeight) {
        Element e = box.getElement();
        if (e == null) {
            return null;
        }
        String nodeName = e.getNodeName();
        // 找到img标签
        if (nodeName.equals("img")) {
            String attribute = e.getAttribute("src");
            FSImage fsImage;
            try {
                // 生成itext图像
                fsImage = buildImage(attribute, uac);
            } catch (BadElementException e1) {
                fsImage = null;
            } catch (IOException e1) {
                fsImage = null;
            }
            if (fsImage != null) {
                // 对图像进行缩放
                if (cssWidth != -1 || cssHeight != -1) {
                    fsImage.scale(cssWidth, cssHeight);
                }
                return new ITextImageElement(fsImage);
            }
        }
        return null;
    }

    /**编解码base64并生成itext图像*/
    protected FSImage buildImage(String srcAttr, UserAgentCallback uac) throws IOException,
            BadElementException {
        FSImage fiImg = null;
        //图片的src要为src="https://img-blog.csdnimg.cn/2022010709130273090.jpg"这种base64格式
        if (srcAttr.toLowerCase().startsWith("data:image/")) {
            String base64Code = srcAttr.substring(srcAttr.indexOf("base64,") + "base64,".length(), srcAttr.length());
            // 解码
            byte[] decodedBytes = Base64.decode(base64Code);
            fiImg = new ITextFSImage(Image.getInstance(decodedBytes));
        } else {
            fiImg = uac.getImageResource(srcAttr).getImage();
        }
        return fiImg;
    }

    public void reset() {
    }

    @Override
    public void remove(Element arg0) {
    }

    @Override
    public void setFormSubmissionListener(FormSubmissionListener arg0) {
    }
}

四、编写实现类

	@RequestMapping("/doDaYing2")
    @ResponseBody
    public String doDaYing2(){
        try{
        	//PDF输出地址
            OutputStream os = new FileOutputStream("D:\\IMG.pdf");
            ITextRenderer renderer = new ITextRenderer();

            // 如果携带图片则加上以下代码,将图片标签转换为Itext自己的图片对象,调用自己写的处理类
            renderer.getSharedContext().setReplacedElementFactory(new ImgInputStream());
            renderer.getSharedContext().getTextRenderer().setSmoothingThreshold(0);
			
			//HTML文件路径,也可以结合上面模板的获取输入流
            String url=new File("D:\\Java_IDEA\\Test\\Test-Mybatis\\src\\main\\resources\\templates\\modules\\Test.html").toURI().toURL().toString();
            renderer.setDocument(url);
            //解决图片相对路径问题,window 上必须用file:/; 后面路径只写到img标签中src的上级目录即图片的当前目录,没有绝对路径就不写      					  //renderer.getSharedContext().setBaseURL("file:/C:/Users/Administrator/Desktop/xse/");
            
            renderer.layout();
            renderer.createPDF(os);
            os.flush();
            os.close();
        }catch(Exception e ){
            e.printStackTrace();
        }
        return "OK";
    }

你可能感兴趣的:(java,ssm,itext)