当前位置: 首页 > 工具软件 > ml-workspace > 使用案例 >

pdf工具类 (pd4ml)

薛华容
2023-12-01

所需jar包和字体包链接:https://download.csdn.net/download/weixin_39530695/11390581

注意:压缩字体包(这个字体包包含常用字体,需要放到WEB-INF目录下)


这篇文章需要有一定基础:如果刚开始接触,请阅读详细的介绍:参考:https://blog.csdn.net/weixin_39530695/article/details/80432050

https://download.csdn.net/download/weixin_39530695/10434460


对于如何把word转换成html请参考这篇文章: 

https://blog.csdn.net/weixin_39530695/article/details/96643166

如果必须得保证转换前后格式一致,建议采用这种方式:

https://blog.csdn.net/weixin_39530695/article/details/98055429


 工具类

package com.common.utils;

import org.apache.log4j.Logger;
import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;
import org.zefer.pd4ml.PD4PageMark;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.*;
import java.security.InvalidParameterException;

/**
 * html转pdf工具类
 *
 * @author  nachuan
 */
public class PdfUtils {

		private static final Logger logger = Logger.getLogger(PdfUtils.class.getName());



	/**
	 * 获取rows
	 * @return
	 */
	private static  int getRows(int allPicNum){
		int rows;
		if (allPicNum % 8 != 0 ) {
			rows = allPicNum/8 + 1;
		}else {
			rows =  allPicNum/8;
		}
		return  rows;
	}
	/**
	 * 获取脚行高
	 * @param rows    case 9:
	 *                 rowHeight = 33;
	 * @return
	 */
	private static int getRowHeight(int rows) {
		int rowHeight;
		if (rows == 0) {
			rowHeight = 40;
		}else if (rows == 1) {
			rowHeight = 65;
		}else if (rows > 1 && rows < 10) {
			rowHeight = 65 - (rows - 2) * 2;

		}else{
			rowHeight = 31;
		}
		return rowHeight;
	}

	/**
	 * 获取头部行高
	 * @param rows    case 9:
	 *                 rowHeight = 33;
	 * @return
	 */
	private static int getHeadRowHeight(int rows) {
		int rowHeight;

		switch (rows){
			case 0:
				rowHeight = 30;
				break;
			case 1:
				rowHeight =49;
				break;
			case 2:
				rowHeight = 38;
				break;
			case 3:
				rowHeight = 35;
				break;
			default:
				rowHeight = 37;
				break;

		}


		return rowHeight;
	}


	/**
	 * 通过html得到一个pdf
	 * @param strReader
	 * @param filePath
	 * @param ysignpicurl
	 * @param bsignpicurl
	 * @param pagehead
	 * @param pagefoot
	 * @return
	 */
	 public static byte[] generatePDF( StringReader strReader,String filePath,String ysignpicurl,String bsignpicurl,String pagehead,String pagefoot,HttpServletRequest req) {
	        try {
	            FileOutputStream fos = new FileOutputStream(filePath);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                PD4ML pd4ml = new PD4ML();
                // A4竖向显示  pd4ml.changePageOrientation(PD4Constants.A4)横向显示
                pd4ml.setPageSize(PD4Constants.A4);
                String path = IpUtils.getProjectRealPath(req) +File.separator + "WEB-INF" ;

				//fonts.jar的配置文件中的值,用于中文乱码
				pd4ml.useTTF(path+File.separator+"fonts",true);
				pd4ml.setDefaultTTFs("STFangsong", "SimSun", "SimHei");

	               
	               //页眉页脚开始--------------------------
					int topValue = 17;
					int leftValue = 28;
					int rightValue = 26;
					int bottomValue = 15;
	                 String unitsValue = "mm";  
	                 int userSpaceWidth = 650;
	               if (unitsValue.equals("mm")) {  
	                   pd4ml.setPageInsetsMM(new Insets(topValue, leftValue,  bottomValue,rightValue));  
	               } else {  
	                   pd4ml.setPageInsets(new Insets(topValue, leftValue, bottomValue,rightValue));  
	               }  
	         
	               pd4ml.setHtmlWidth(userSpaceWidth);
					pd4ml.adjustHtmlWidth();
					pd4ml.disableHyperlinks();
	              
	            
	              StringBuilder sbhead = new StringBuilder();
	              sbhead.append("<html><span style=\"font-family:STFangsong; \">" + pagehead);
	              sbhead.append("</span><hr/></html>");
	              String pageHeader = sbhead.toString() ;  
	            	StringBuilder sb = new StringBuilder();
	            	sb.append("<html><head> <meta charset=\"UTF-8\"> </head><body>");
	            	sb.append("<div  ><span style=\"font-family:STFangsong; font-size:28px ;font-weight: 320;\">");
	            	sb.append(":</span>	<img  style=\"width: 90px; height: 40px;background-color:beige;  \" src=\"" + ysignpicurl);
	            	sb.append("\" />	");
	            	sb.append("<span style=\"font-family:STFangsong; font-size:28px ; font-weight: 320;\">");
	            	sb.append(":</span><img  style=\"width: 90px; height: 40px;background-color:beige;  \" src=\"" + bsignpicurl);
	            	sb.append("\" /></div>	");
	            	sb.append("<hr/><span>" + pagefoot);
	            	sb.append("</span >");

	            	sb.append("<center>页数$[page]/$[total]</center></body></html>");
	            	String pageFooter = sb.toString();
				setPageHead(pd4ml, pageHeader);
				setPageFoot(pd4ml, pageFooter, 70);


		            pd4ml.render(strReader, fos);
	               return os.toByteArray();  
	       } catch (FileNotFoundException e) {  
	           e.printStackTrace();  
	       } catch (InvalidParameterException e) {  
	           e.printStackTrace();  
	       } catch (IOException e) {  
	           e.printStackTrace();  
	       }  
	       return null;  
	            
	             
	       }

	/**
	 * 上传图片
	 * @param strReader
	 * @param filePath
	 * @param allusersignpic
	 * @param pagehead
	 * @param pagefoot
	 * @param req
	 * @return
	 */
	 public synchronized static boolean generatelistPDF(StringReader strReader,String filePath,String allusersignpic,String pagehead,String pagefoot,HttpServletRequest req) {
			 try {
				 FileOutputStream fos = new FileOutputStream(filePath);
			 ByteArrayOutputStream os = new ByteArrayOutputStream();
			 PD4ML pd4ml = new PD4ML();    

			 // A4竖向显示  pd4ml.changePageOrientation(PD4Constants.A4)横向显示
			 pd4ml.setPageSize(PD4Constants.A4);


			 String path = IpUtils.getProjectRealPath(req) +File.separator + "WEB-INF" ;

			 //测试完了要注释
//		    	String path = "C:\\javatools\\ideaworkspace_1\\mydir\\src\\main\\webapp\\WEB-INF";
			 //fonts.jar的配置文件中的值,用于中文乱码
			 pd4ml.useTTF(path+File.separator+"fonts",true);
			 pd4ml.setDefaultTTFs("STFangsong", "SimSun", "SimHei");
			 pd4ml.enableDebugInfo();


			 
			 //页眉页脚开始--------------------------
				 int topValue = 17;
				 int leftValue = 28;
				 int rightValue = 26;
				 int bottomValue = 15;
			 String unitsValue = "mm";  
			 int userSpaceWidth = 650;
			 if (unitsValue.equals("mm")) {  
				 pd4ml.setPageInsetsMM(new Insets(topValue, leftValue,  bottomValue,rightValue));  
			 } else {  
				 pd4ml.setPageInsets(new Insets(topValue, leftValue, bottomValue,rightValue));  
			 }  
			 
			 pd4ml.setHtmlWidth(userSpaceWidth);

				 pd4ml.adjustHtmlWidth();
				 pd4ml.disableHyperlinks();
			 
			 StringBuilder sbhead = new StringBuilder();
			 sbhead.append("<html><span style=\"font-family:STFangsong; \">" + pagehead);
			 sbhead.append("</span><hr/></html>");
			 String pageHeader = sbhead.toString() ;  
			 StringBuilder sb = new StringBuilder();
			 sb.append("<html><head> <meta charset=\"UTF-8\"> </head><body>");
			 sb.append("<div>");
			 sb.append(allusersignpic);
			 sb.append("</div>");
			 sb.append("<hr/><span>" + pagefoot);
			 sb.append("</span >");
			 

			 
			 sb.append("<center>页数$[page]/$[total]</center></body></html>");
			 System.out.println("pagefooter:" + sb.toString());
			 String pageFooter = sb.toString();
				 setPageHead(pd4ml, pageHeader);
				 setPageFoot(pd4ml, pageFooter, 100);


				 //======================================================
			 pd4ml.render(strReader, fos);
			 return true;
		 } catch (Exception e) {
			 e.printStackTrace();  
			 return  false;
		 }

	 }




    /**
	 * 设置页尾
	 * @param pd4ml
	 * @param pageFooter
	 * @param i
	 */
	private static void setPageFoot(PD4ML pd4ml, String pageFooter, int i) {
		if (null != pageFooter && !"".equals(pageFooter.trim())) {
			PD4PageMark footerMark = new PD4PageMark();
			footerMark.setAreaHeight(i);
			footerMark.setInitialPageNumber(1);
			footerMark.setPageNumberAlignment(1);
			if (pageFooter.toUpperCase().startsWith("<HTML>") && pageFooter.toUpperCase().endsWith("</HTML>")) {
				footerMark.setHtmlTemplate(pageFooter);
			} else {
				footerMark.setTitleAlignment(PD4PageMark.RIGHT_ALIGN);
				footerMark.setTitleTemplate(pageFooter);


			}
			footerMark.setPagesToSkip(0);
			pd4ml.setPageFooter(footerMark);
		}
	}

	public static byte[] wordhtml2pdf(StringReader strReader,String filePath,String pagehead,String pagefoot,HttpServletRequest req) {

		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(filePath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
			PD4ML pd4ml = new PD4ML();

			String path = "";

		if (MyWindowsUtil.isWindowsOS()) {
			path = "C:\\javatools\\ideaworkspace_1\\mydir\\src\\main\\webapp\\WEB-INF";
		}else {
			path = IpUtils.getProjectRealPath(req) +File.separator + "WEB-INF" ;
		}
			//fonts.jar的配置文件中的值,用于中文乱码
		try {
			pd4ml.useTTF(path+File.separator+"fonts",true);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			logger.error("设置字体错误");
		}
		pd4ml.setDefaultTTFs("STFangsong", "SimSun", "SimHei");
			// A4竖向显示  pd4ml.changePageOrientation(PD4Constants.A4)横向显示
            pd4ml.setPageSize(PD4Constants.A4);

            pd4ml.enableDebugInfo();

			//页眉页脚开始--------------------------
			int topValue = 17;
			int leftValue = 28;
			int rightValue = 26;
			int bottomValue = 15;
			String unitsValue = "mm";
			int userSpaceWidth = 650;
			if (unitsValue.equals("mm")) {
				pd4ml.setPageInsetsMM(new Insets(topValue, leftValue,  bottomValue,rightValue));
			} else {
				pd4ml.setPageInsets(new Insets(topValue, leftValue, bottomValue,rightValue));
			}
			pd4ml.adjustHtmlWidth();
			pd4ml.disableHyperlinks();
			pd4ml.setHtmlWidth(userSpaceWidth);



			StringBuilder sbhead = new StringBuilder();
			sbhead.append("<html><span style=\"font-family:STFangsong; \">" + pagehead);
			sbhead.append("</span><hr/></html>");
			String pageHeader = sbhead.toString() ;
			StringBuilder sb = new StringBuilder();
			sb.append("<hr/><span>" + pagefoot);



			sb.append("<center>页数$[page]/$[total]</center></body></html>");
			System.out.println("pagefooter:" + sb.toString());
			String pageFooter = sb.toString();
		setPageHead(pd4ml, pageHeader);
		setPageFoot(pd4ml, pageFooter, 100);


		//======================================================
		try {
			pd4ml.render(strReader, fos);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return os.toByteArray();


	}

	/**
	 * 设置页首
	 * @param pd4ml
	 * @param pageHeader
	 */
	private static void setPageHead(PD4ML pd4ml, String pageHeader) {
		if (null != pageHeader && !"".equals(pageHeader.trim())) {
			PD4PageMark headerMark = new PD4PageMark();
			headerMark.setAreaHeight(30);
			headerMark.setInitialPageNumber(1);
			if (pageHeader.toUpperCase().startsWith("<HTML>") && pageHeader.toUpperCase().endsWith("</HTML>")) {
				headerMark.setHtmlTemplate(pageHeader);
			} else {
				headerMark.setTitleTemplate(pageHeader);
			}
			pd4ml.setPageHeader(headerMark);
		}
	}




		/**
		 * 获取files
		 * @param folder
		 * @return
		 * @throws IOException
		 */
		private static String[] getFiles(String folder) throws IOException {
			File _folder = new File(folder);
			String[] filesInFolder;

			if(_folder.isDirectory()) {
				filesInFolder = _folder.list();
				return filesInFolder;
			} else {
				throw new IOException("Path is not a directory");
			}
		}



}

 

 类似资料: