瀏覽代碼

html转pdf切换成OpenPDF

sakuya 3 年之前
父節點
當前提交
0df91bf494

+ 0 - 30
eladmin-system/src/main/java/me/zhengjie/application/admin/controller/NotaryNoteController.java

@@ -7,14 +7,10 @@ import me.zhengjie.annotation.rest.AnonymousGetMapping;
 import me.zhengjie.application.admin.controller.vo.NotaryNoteVo;
 import me.zhengjie.application.admin.service.NotaryNoteService;
 import me.zhengjie.base.AppBaseResponse;
-import me.zhengjie.base.util.HtmlConvertPdf;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
 import javax.validation.Valid;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
 
 @RestController
 @RequestMapping("/api/note")
@@ -50,30 +46,4 @@ public class NotaryNoteController {
     public String generateTestPdf(@RequestParam String modelId, @RequestParam String businessNo) {
         return notaryNoteService.generateTestPdf(modelId, businessNo);
     }
-
-    public static void main(String[] args) {
-        try {
-            String html = readString("/Users/sakuya/Downloads/dbfdfd566ef94895805c67ceb5f9bd05.html");
-            HtmlConvertPdf.converPdf(html, "/Users/sakuya/Downloads/eaf26674fdce450e85591e1ad74fe6e9.pdf");
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-    private static String readString(String filePath) {
-        String str = "";
-        File file = new File(filePath);
-        try {
-            FileInputStream in = new FileInputStream(file);
-            // size 为字串的长度 ,这里一次性读完
-            int size = in.available();
-            byte[] buffer = new byte[size];
-            in.read(buffer);
-            in.close();
-            str = new String(buffer, "UTF-8");
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-        return str;
-    }
 }

+ 5 - 7
eladmin-system/src/main/java/me/zhengjie/application/admin/service/impl/AdminOrderServiceImpl.java

@@ -12,6 +12,7 @@ import java.util.Map;
 import java.util.Set;
 import java.util.stream.Collectors;
 
+import me.zhengjie.base.util.*;
 import me.zhengjie.dao.mybatis.entity.*;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
@@ -37,17 +38,12 @@ import me.zhengjie.application.admin.controller.vo.PartyEntity;
 import me.zhengjie.application.admin.service.AdminOrderService;
 import me.zhengjie.application.admin.service.OrderCochainService;
 import me.zhengjie.application.admin.service.SmsTemplateService;
-import me.zhengjie.application.bank.controller.vo.BankOrderVO;
 import me.zhengjie.application.bank.service.BankOrderService;
 import me.zhengjie.application.bank.service.FileInfoService;
 import me.zhengjie.base.AppBaseResponse;
 import me.zhengjie.base.AppResultData;
 import me.zhengjie.base.ResultCode;
 import me.zhengjie.base.plus.QueryWrapperUtil;
-import me.zhengjie.base.util.ApplicationContextUtil;
-import me.zhengjie.base.util.BeanCopyUtils;
-import me.zhengjie.base.util.FileUploadUtil;
-import me.zhengjie.base.util.StatusEnum;
 import me.zhengjie.base.util.StatusEnum.NotaryStatusEnum;
 import me.zhengjie.dao.mybatis.ContractOrderRepository;
 import me.zhengjie.dao.mybatis.ModelRepository;
@@ -133,6 +129,8 @@ public class AdminOrderServiceImpl implements AdminOrderService {
 	SysUserMapper userMapper;
 	@Autowired
 	SmsTemplateService smsTemplateService;
+	@Autowired
+    HtmlConvertToPdf htmlConvertToPdf;
 
 	@Override
 	public AppBaseResponse<List<NotaryOrderQueryRsp>> query(NotaryOrderQueryReq req) {
@@ -416,7 +414,7 @@ public class AdminOrderServiceImpl implements AdminOrderService {
 				ModelConstant.MODEL_TYPE_NOTARIZATION, "1");
 		String content = modelSynthesizerDomain.composeNotarizationTemplate(currentNum, req.getContent());
 		String htmlPath = FileUploadUtil.saveHtml(content, contractOrderEntity.getBusinessNo());
-		String pdfPath = FileUploadUtil.savePdf(content, contractOrderEntity.getBusinessNo());
+		String pdfPath = FileUploadUtil.savePdf(content, contractOrderEntity.getBusinessNo(), htmlConvertToPdf);
 		//
 		OrderFileEntity notaryOrderFile = orderFileRepository.getOrderNotarization(contractOrderEntity.getBusinessNo());
 		OrderFileEntity saveOrder = new OrderFileEntity();
@@ -502,7 +500,7 @@ public class AdminOrderServiceImpl implements AdminOrderService {
 	public AppBaseResponse<String> previewNotarizationPdf(NotaryOrderQueryReq req) {
 		AppBaseResponse<String> response = new AppBaseResponse<>();
 		String html = modelSynthesizerDomain.composeNotarizationTemplate(1000, req.getContent());
-		String url = FileUploadUtil.getPreviewUrl(FileUploadUtil.savePdf(html, req.getBusinessNo()));
+		String url = FileUploadUtil.getPreviewUrl(FileUploadUtil.savePdf(html, req.getBusinessNo(), htmlConvertToPdf));
 		response.setData(new AppResultData<String>(url));
 		return response;
 	}

+ 3 - 2
eladmin-system/src/main/java/me/zhengjie/application/admin/service/impl/NotaryNoteServiceImpl.java

@@ -40,6 +40,7 @@ public class NotaryNoteServiceImpl implements NotaryNoteService {
 	private final OrderFileRepository orderFileRepository;
 	private final ModelSynthesizerDomain modelSynthesizerDomain;
 	private final ModelMapper modelMapper;
+	private final HtmlConvertToPdf htmlConvertToPdf;
 
 	@Override
 	public JSONObject getNotaryNoteByType(NotaryNoteVo notary) {
@@ -84,7 +85,7 @@ public class NotaryNoteServiceImpl implements NotaryNoteService {
 		NotaryOfficeEntity officeEntity = notaryOfficeMapper.selectById(userDto.getOrgId().split("_")[1]);
 		String htmlContent = modelSynthesizerDomain.composeNoteTemplate(notaryNoteDtoList, userDto.getNickName(), notary.getBusinessNo());
 		String htmlpath = FileUploadUtil.saveHtml(htmlContent, notary.getBusinessNo());
-		String pdfPath = FileUploadUtil.savePdf(htmlContent, notary.getBusinessNo());
+		String pdfPath = FileUploadUtil.savePdf(htmlContent, notary.getBusinessNo(), htmlConvertToPdf);
 		//
 		ModelEntity modelEntity = modelRepository.getModelEntity(notary.getProdId(), notary.getContractType(), String.valueOf(officeEntity.getId()), ModelConstant.MODEL_TYPE_NOTE, ModelConstant.MODEL_STATUS_ENABLE);
 		OrderFileEntity orderFile = new OrderFileEntity();
@@ -128,6 +129,6 @@ public class NotaryNoteServiceImpl implements NotaryNoteService {
 		ContractOrderEntity order = contractOrderRepository.getContractOrderWithBizNo(businessNo);
 		String content = modelSynthesizerDomain.composeNotarizationPreview(order, model.getContent());
 		String html = modelSynthesizerDomain.composeNotarizationTemplate(1000, content);
-		return FileUploadUtil.getPreviewUrl(FileUploadUtil.savePdf(html, businessNo));
+		return FileUploadUtil.getPreviewUrl(FileUploadUtil.savePdf(html, businessNo, htmlConvertToPdf));
 	}
 }

+ 2 - 97
eladmin-system/src/main/java/me/zhengjie/base/util/FileUploadUtil.java

@@ -23,7 +23,6 @@ import me.zhengjie.base.util.StatusEnum.StepStatusEnum;
 import me.zhengjie.application.bank.controller.vo.FileUploadVO;
 import me.zhengjie.application.admin.controller.vo.FileVo;
 import me.zhengjie.application.bank.controller.vo.ImageUploadVO;
-import me.zhengjie.base.config.AppConfigInfo;
 import me.zhengjie.base.file.FileHandle;
 import me.zhengjie.base.file.FileHandleVo;
 
@@ -36,7 +35,6 @@ import me.zhengjie.base.file.FileHandleVo;
  */
 @Slf4j
 public class FileUploadUtil {
-
 	private static FileHandle fileHandle;
 	// 创建临时目录
 	private static String tempDir;
@@ -263,25 +261,6 @@ public class FileUploadUtil {
 
 	}
 
-//	public static String saveHtml(String html, String businessNo) {
-//		if (html == null) {
-//			return null;
-//		}
-//		String uploadPath = AppConfigInfo.APP_UPLOAD_PATH;
-//		// 拼接文件路径
-//		String fileName = UUIDGenerator.uuid() + ".html";
-//		String imagePath = "no" + businessNo + "/" + fileName;
-//		String filePath = uploadPath + imagePath;
-//		try {
-//			// File file, String data, Charset charset
-//			FileUtils.writeStringToFile(new File(filePath), html, "UTF-8");
-//			return imagePath;
-//		} catch (IOException e) {
-//			log.info("上传图片失败:" + e.getLocalizedMessage());
-//			return null;
-//		}
-//	}
-
 	public static String saveHtml(String html, String businessNo) {
 		if (html == null) {
 			return null;
@@ -305,27 +284,6 @@ public class FileUploadUtil {
 		}
 	}
 
-//	public static String saveHtml(String filePath, String html) {
-//		if (html == null) {
-//			return null;
-//		}
-//		// 拼接文件路径
-//
-//		try {
-//			ByteArrayInputStream bis = new ByteArrayInputStream(html.getBytes("UTF-8"));
-//			// File file, String data, Charset charset
-//			FileHandleVo fileHandlevo = new FileHandleVo();
-//			fileHandlevo.setFilePath(filePath);
-//			fileHandlevo.setContentType("text/html");
-//			fileHandlevo.setInputStream(bis);
-//			fileHandle.uploadFileStream(fileHandlevo);
-//			bis.close();
-//			return filePath;
-//		} catch (Exception e) {
-//			log.error("上传图片失败:" + e.getLocalizedMessage());
-//			return null;
-//		}
-//	}
 	/**
 	 * 上传文件通过文件的流
 	 * 
@@ -398,25 +356,6 @@ public class FileUploadUtil {
 
 	}
 
-//	public static String savePdf(String html, String businessNo) {
-//		if (html == null) {
-//			return null;
-//		}
-//
-//		String uploadPath = AppConfigInfo.APP_UPLOAD_PATH;
-//		// 拼接文件路径
-//		String fileName = UUIDGenerator.uuid() + ".pdf";
-//		String path = "no" + businessNo + "/" + fileName;
-//		String filePath = uploadPath + path;
-//		try {
-//			// File file, String data, Charset charset
-//			HtmlConvertPdf.createPdfFile(html, filePath);
-//			return path;
-//		} catch (Exception e) {
-//			log.info("转换pdf失败:" + e.getLocalizedMessage());
-//			return null;
-//		}
-//	}
 	/**
 	 * Return the absolute temp dir for given web server.
 	 * 
@@ -436,7 +375,7 @@ public class FileUploadUtil {
 		}
 	}
 
-	public static String savePdf(String html, String businessNo) {
+	public static String savePdf(String html, String businessNo, HtmlConvertToPdf htmlConvertToPdf) {
 		if (html == null) {
 			return null;
 		}
@@ -448,7 +387,7 @@ public class FileUploadUtil {
 		InputStream inputStream = null;
 		try {
 			// File file, String data, Charset charset
-			HtmlConvertPdf.converPdf(html, sourceFilePath);
+			htmlConvertToPdf.converPdf(html, sourceFilePath);
 			inputStream = new FileInputStream(sourceFilePath);
 			// 这里需要把转换完成的删除掉
 			String contentType = "application/pdf";
@@ -471,40 +410,6 @@ public class FileUploadUtil {
 		}
 	}
 
-	public static String createPdf(String html, String pdfPath) {
-
-		if (html == null) {
-			return null;
-		}
-		String uploadPath = tempDir;
-
-		String sourceFilePath = uploadPath + pdfPath;
-		InputStream inputStream = null;
-		try {
-			// File file, String data, Charset charset
-			HtmlConvertPdf.converPdf(html, sourceFilePath);
-			inputStream = new FileInputStream(sourceFilePath);
-			// 这里需要把转换完成的删除掉
-			String contentType = "application/pdf";
-			// 通过流上传
-			// fileHandle.uploadFilePath(path, filePath, contentType);
-			FileHandleVo fileHandlevo = new FileHandleVo();
-			fileHandlevo.setFilePath(pdfPath);
-			fileHandlevo.setSourceFilePath(sourceFilePath);
-			fileHandlevo.setContentType(contentType);
-			fileHandlevo.setInputStream(inputStream);
-			fileHandle.uploadFileStream(fileHandlevo);
-			IoUtil.close(inputStream);
-			// 这个删除文件留给具体的上传处理
-			FileUtils.deleteQuietly(new File(sourceFilePath));
-			return pdfPath;
-		} catch (Exception e) {
-			log.error("转换pdf失败:" + e.getLocalizedMessage());
-			return null;
-		}
-
-	}
-
 	/**
 	 * 产生图片预览
 	 * 

+ 36 - 12
eladmin-system/src/main/java/me/zhengjie/base/util/HtmlConvertPdf.java

@@ -3,10 +3,14 @@ package me.zhengjie.base.util;
 import com.openhtmltopdf.outputdevice.helper.BaseRendererBuilder;
 import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
 import lombok.extern.slf4j.Slf4j;
+import me.zhengjie.sign.connector.HttpClient;
 import org.apache.commons.io.FileUtils;
 import org.jsoup.Jsoup;
 import org.jsoup.helper.W3CDom;
 import org.jsoup.nodes.Document;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
 import org.zefer.pd4ml.PD4Constants;
 import org.zefer.pd4ml.PD4ML;
 
@@ -15,7 +19,7 @@ import java.io.File;
 import java.io.FileOutputStream;
 import java.io.OutputStream;
 import java.io.StringReader;
-import java.nio.file.FileSystems;
+import java.nio.file.*;
 
 /**
  * https://pd4ml.com/api/org/zefer/pd4ml/PD4ML.html api文档
@@ -25,11 +29,30 @@ import java.nio.file.FileSystems;
  * @author humuyu
  * 
  */
+@Component
 @Slf4j
-public class HtmlConvertPdf {
+public class HtmlConvertToPdf implements InitializingBean {
+	@Value("${html2Pdf.simsumPath}")
+	private String simsumPath;
+	@Value("${html2Pdf.simfangPath}")
+	private String simfangPath;
+	@Value("${html2Pdf.toolName}")
+	private String toolName;
 	private static final String CONVERT_TYPE_PD4ML = "PD4ML";
-	private static final String CONVERT_TYPE_OPENPDF = "OPENPDF";
-	private static final String CONVERT_TYPE_CURRENT = CONVERT_TYPE_OPENPDF;
+	private static final String CONVERT_TYPE_OPENPDF = "OpenPDF";
+
+	@Override
+	public void afterPropertiesSet() throws Exception {
+		String[] fontPath = {simsumPath, simfangPath};
+		for (String path : fontPath) {
+			String aimPath = path.substring(path.indexOf("/"));
+			Path temp = Paths.get(new File(HtmlConvertToPdf.class.getClassLoader().getResource("").getPath().concat(aimPath)).getAbsolutePath());
+			if (Files.exists(temp)) {
+				Files.delete(temp);
+			}
+			Files.copy(HtmlConvertToPdf.class.getClassLoader().getResourceAsStream(path), temp, StandardCopyOption.REPLACE_EXISTING);
+		}
+	}
 
 	/**
 	 * 将html转换成pdf
@@ -38,10 +61,10 @@ public class HtmlConvertPdf {
 	 * @param destPath
 	 * @throws Exception
 	 */
-	public static void converPdf(String html, String destPath) throws Exception {
-		if (CONVERT_TYPE_OPENPDF.equals(CONVERT_TYPE_CURRENT)) {
+	public void converPdf(String html, String destPath) throws Exception {
+		if (CONVERT_TYPE_OPENPDF.equals(toolName)) {
 			convertPdfWithOpenPDF(html, destPath);
-		} else if (CONVERT_TYPE_PD4ML.equals(CONVERT_TYPE_CURRENT)) {
+		} else if (CONVERT_TYPE_PD4ML.equals(toolName)) {
 			convertPdfWithPD4ML(html, destPath);
 		}
 	}
@@ -53,7 +76,7 @@ public class HtmlConvertPdf {
 	 * @param destPath 输出的PDF文件路径
 	 * @throws Exception
 	 */
-	private static void convertPdfWithPD4ML(String html, String destPath) throws Exception {
+	private void convertPdfWithPD4ML(String html, String destPath) throws Exception {
 		File file = new File(destPath);
 		FileUtils.writeStringToFile(file, "", "UTF-8");
 		FileOutputStream outFile = new FileOutputStream(file);
@@ -77,7 +100,7 @@ public class HtmlConvertPdf {
 	 * @param destPath
 	 * @throws Exception
 	 */
-	private static void convertPdfWithOpenPDF(String html, String destPath) throws Exception {
+	private void convertPdfWithOpenPDF(String html, String destPath) throws Exception {
 		//加载html文件
 		Document document = Jsoup.parse(html);
 		document.outputSettings().syntax(Document.OutputSettings.Syntax.html);
@@ -93,10 +116,11 @@ public class HtmlConvertPdf {
 		builder.withW3cDocument(new W3CDom().fromJsoup(document), baseUri);
 
 		//引入指定字体,注意字体名需要和css样式中指定的字体名相同
-		String fontPath = HtmlConvertPdf.class.getClassLoader().getResource("").getPath().concat("font");
+		String fontPath = HtmlConvertToPdf.class.getClassLoader().getResource("").getPath();
 		System.out.println(fontPath);
-		builder.useFont(new File(fontPath + "/simsun.ttf"), "SimSun", 0, BaseRendererBuilder.FontStyle.NORMAL, true);
-		builder.useFont(new File(fontPath + "/simfang.ttf"), "simfang", 0, BaseRendererBuilder.FontStyle.NORMAL, true);
+		builder.useFont(new File(fontPath + simsumPath), "SimSun", 0, BaseRendererBuilder.FontStyle.NORMAL, true);
+		builder.useFont(new File(fontPath + simfangPath), "simfang", 0, BaseRendererBuilder.FontStyle.NORMAL, true);
+
 		builder.run();
 	}
 }

+ 3 - 2
eladmin-system/src/main/java/me/zhengjie/domain/model/ModelSynthesizerDomain.java

@@ -37,6 +37,7 @@ public class ModelSynthesizerDomain {
     private final ProvinceMapper provinceMapper;
     private final ApplicationContextUtil contextUtil;
     private final FileInfoMapper fileInfoMapper;
+    private final HtmlConvertToPdf htmlConvertToPdf;
 
     /**
      * 生成普通公证文书
@@ -56,7 +57,7 @@ public class ModelSynthesizerDomain {
             fileEntity.setSortNum(m.getSort());
             String html = composeCommonTemplateWithData(businessNo, m.getContent(), "", false, null);
             String htmlPath = FileUploadUtil.saveHtml(html, businessNo);
-            String pdfPath = FileUploadUtil.savePdf(html, businessNo);
+            String pdfPath = FileUploadUtil.savePdf(html, businessNo, htmlConvertToPdf);
             fileEntity.setHtmlUrl(htmlPath);
             fileEntity.setPdfUrl(pdfPath);
             fileEntity.setCreateTime(new Date());
@@ -83,7 +84,7 @@ public class ModelSynthesizerDomain {
             saveFile.setId(fileEntity.getId());
             String html = composeCommonTemplateWithData(businessNo, m.getContent(), notaryUser.getNickName(), true, signUser);
             String htmlPath = FileUploadUtil.saveHtml(html, businessNo);
-            String pdfPath = FileUploadUtil.savePdf(html, businessNo);
+            String pdfPath = FileUploadUtil.savePdf(html, businessNo, htmlConvertToPdf);
             saveFile.setHtmlUrl(htmlPath);
             saveFile.setPdfUrl(pdfPath);
             saveFile.setUpdateTime(new Date());