java实现html转pdf

2023-05-16

1.需求:将一个html页面转成pdf格式。
2.方法:在实现之前先考虑一个问题,pdf是前端生成还是后端生成。这里采用pdfbox+itext(PDF文件名可自定义)技术在服务端生成。
优点:免费,不需要安转软件,速度快,对于开发者而言,开发中仅需导入相应jar,且易部署。
缺点:对于html标签比较严格。

3.实现:
3.1 需要的jar
itext-2.0.8.jar+pdfbox-2.0.19.jar

3.2 准备好html页面代码(注意:这里需要手动指定字体):

sHtml += "<!DOCTYPE html[<!ENTITY nbsp ' '>]>";
	sHtml += "<html>";
	sHtml += "<head>";
	sHtml += "</head>";
	sHtml += "<body style='font-family:SimSun !important;'>";
	sHtml += "<h1>这里是测试PDF代码部分</h1>";
	sHtml += "</body>";
	sHtml += "</html>";

3.3 服务端开始生成PDF文件:

public static void toPdf(String sHtml) {
		try {
			//创建PDf文件
			ITextRenderer renderer = new ITextRenderer();
			ITextFontResolver fontResolver = renderer.getFontResolver();
			 
			//C:/WINDOWS/Fonts/SimSun.ttc 系统自带的语言包,直接引用
			fontResolver.addFont("C:/WINDOWS/Fonts/SimSun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			fontResolver.addFont("C:/WINDOWS/Fonts/Arial.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);// 宋体字
			 
			String sDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
    		String sTime = new SimpleDateFormat("HHmmssSSS").format(new Date());
			
			//指定文件存放路径
			URL sUrlPath = 当前类名.class.getResource("/");
			String sPath = sUrlPath.toURI().getPath();
			sPath1 = sPath.replace("WEB-INF/classes/", "");
			String sPathFolder = sPath+sDate+"\\";
			
			File filePath = new File(sPathFolder);
    		if(!filePath.exists()  && !filePath.isDirectory()){
    			filePath.mkdirs();
    		}
			
    		String sFileName = sDate+sTime+".pdf";
    		
			String sPathSave = sPathFolder+sFileName;
			OutputStream os = new FileOutputStream(sPathSave);
			 
			//使用有setDocumentFromString()方法的jar包
			renderer.setDocumentFromString(sHtml);
			renderer.layout();
			renderer.createPDF(os);
			os.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
	}

3.4 前端页面发起请求,服务端将生成的PDF文件返回。

String sTitle = "测试PDF文件名";
File file = new File(sFileUrl);//这里的sFileUrl即上面PDF保存路径
	try {
	    OutputStream outputStream = response.getOutputStream();
	     //加载pdf附件到PDF流中
	     PDDocument document = PDDocument.load(new FileInputStream(file));
	    
	    response.reset();
	    response.setContentType("application/pdf;charset=UTF-8");
	    response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(sTitle, "UTF-8"));
	     
	     
	    response.setContentType("application/pdf;charset=UTF-8");
	    //从PDF流中获得PDF文档属性对象
	    PDDocumentInformation info = document.getDocumentInformation();
	    //设置PDF文档属性对象的文件名称(最重要的环节)
	    info.setTitle(sTitle);
	    document.setDocumentInformation(info);
	    
	    //修改完直接输出到响应体中
	    document.save(outputStream);
	    outputStream.close();
	    document.close();
	    out.clear();  
		out = pageContext.pushBody();
	    
	} catch (Exception e) {
	    
	}

完成!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java实现html转pdf 的相关文章