PdfHelp.java 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. package com.qxgmat.help;
  2. //import com.spire.pdf.PdfDocument;
  3. //import com.spire.pdf.PdfPageBase;
  4. //import com.spire.pdf.graphics.*;
  5. //import com.spire.pdf.widget.PdfPageCollection;
  6. import com.itextpdf.text.*;
  7. import com.itextpdf.text.Font;
  8. import com.itextpdf.text.Rectangle;
  9. import com.itextpdf.text.pdf.*;
  10. import com.qxgmat.data.dao.entity.User;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.beans.factory.annotation.Value;
  15. import org.springframework.stereotype.Service;
  16. import java.awt.*;
  17. import java.awt.Image;
  18. import java.awt.image.BufferedImage;
  19. import java.io.File;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. /**
  23. * Created by GaoJie on 2017/11/3.
  24. */
  25. @Service
  26. public class PdfHelp {
  27. private static final Logger logger = LoggerFactory.getLogger(PdfHelp.class);
  28. @Value("${upload.local_path}")
  29. private String localPath;
  30. @Value("${upload.web_url}")
  31. private String webUrl;
  32. @Value("${upload.offline_path}")
  33. private String offlinePath;
  34. @Value("${upload.offline_url}")
  35. private String offlineUrl;
  36. @Value("${upload.water}")
  37. private String water;
  38. private BaseFont font;
  39. private int top = 72;
  40. private int left = 93;
  41. private int size = 10;
  42. @Autowired
  43. private void getFont(@Value("${upload.font}") String path) throws IOException, DocumentException {
  44. FontFactory.registerDirectories();
  45. String sub = "";
  46. if (path.toLowerCase().endsWith(".ttc")){
  47. sub += ",1";
  48. }
  49. if (path.startsWith(".")){
  50. // 相对路径,从resource中获取
  51. // logger.debug("{}, {}", path, this.getClass().getClassLoader().getResource(path.replaceFirst(".","")));
  52. // logger.debug("{}, {}", path, this.getClass().getClassLoader().getResource(path));
  53. try {
  54. font = BaseFont.createFont(this.getClass().getClassLoader().getResource(path.replaceFirst(".","")).toString()+sub,BaseFont.IDENTITY_H,true);
  55. }catch (Exception e){
  56. font = BaseFont.createFont(this.getClass().getClassLoader().getResource(path).toString()+sub,BaseFont.IDENTITY_H,true);
  57. }
  58. }else{
  59. font = BaseFont.createFont(path+sub,BaseFont.IDENTITY_H,true);
  60. }
  61. }
  62. public static BufferedImage toBufferedImage(Image img)
  63. {
  64. if (img instanceof BufferedImage)
  65. {
  66. return (BufferedImage) img;
  67. }
  68. // Create a buffered image with transparency
  69. BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
  70. // Draw the image on to the buffered image
  71. Graphics2D bGr = bimage.createGraphics();
  72. bGr.drawImage(img, 0, 0, null);
  73. bGr.dispose();
  74. // Return the buffered image
  75. return bimage;
  76. }
  77. public String[] getUserWater(User user){
  78. // 2份水印文字
  79. String mobile = user.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})","$1****$2");
  80. String name = (user.getRealStatus() > 0? user.getRealName().replaceAll("(.{1}).*(.{1})?","$1*$2 ") : "") + mobile;
  81. String qx = "千行ID "+String.format("%04d", user.getId());
  82. return new String[]{name, qx};
  83. }
  84. public String getOfflineUrl(String offline){
  85. return offline.replace(offlinePath, offlineUrl);
  86. }
  87. public String generatePdfImage(User user, String pdfUrl, boolean force) throws IOException, DocumentException {
  88. File dir = new File(offlinePath);
  89. if (!dir.exists()) {
  90. dir.mkdirs();
  91. }
  92. String pdfFile = pdfUrl.replace(webUrl, localPath);
  93. String dest = pdfFile.replace(".pdf", String.format("_%d.pdf", user.getId())).replace(localPath, offlinePath);
  94. File file = new File(dest);
  95. if (!force && file.exists()){
  96. return dest;
  97. }else if(file.exists()){
  98. file.delete();
  99. }
  100. String[] waters = getUserWater(user);
  101. PdfReader reader = new PdfReader(pdfFile);
  102. // 如果是web项目,直接下载应该放到response的流里面
  103. // PdfStamper stamp = new PdfStamper(reader,response.getOutputStream());
  104. // 添加水印之后的pdf文件
  105. PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  106. int pageSize = reader.getNumberOfPages();
  107. PdfContentByte under;
  108. for (int i = 1; i<=pageSize;i++){
  109. under = stamper.getOverContent(i);
  110. Rectangle r = reader.getPageSize(i);
  111. float width = r.getWidth();
  112. float height = r.getHeight();
  113. float[] a = new float[]{top, (height/2-top)/2-size/2 + top, height / 2-size/2, (height/2 + (height - top - height/2)/2)-size/2, height-top-size};
  114. for (int j = 0; j < 5; j ++){
  115. AddTextWatermark(under, waters[0], Element.ALIGN_LEFT, left, a[j]);
  116. AddTextWatermark(under, waters[1], Element.ALIGN_CENTER, width / 2,a[j]);
  117. AddTextWatermark(under, waters[0], Element.ALIGN_RIGHT, width - left,a[j]);
  118. }
  119. }
  120. stamper.close();
  121. reader.close();
  122. return dest;
  123. }
  124. void AddTextWatermark(PdfContentByte content, String textWatermark, int alignment, float width, float y){
  125. content.saveState();
  126. // Font f = new Font(font, 10);
  127. // f.setColor(0,0,0);
  128. // f.setStyle(Font.NORMAL);
  129. PdfGState gs = new PdfGState();
  130. gs.setFillOpacity(0.2f);
  131. content.setGState(gs);
  132. // Phrase p = new Phrase(textWatermark, f);
  133. content.beginText();
  134. content.setColorFill(new BaseColor(0,0,0));// 文字水印 颜色
  135. content.setFontAndSize(font, size);// 文字水印 字体及字号
  136. // content.setTextMatrix(0, 0);// 文字水印 起始位置
  137. content.showTextAligned(alignment, textWatermark, width, y, 0);
  138. content.endText();
  139. // 在页面中添加多次,计算为止
  140. // ColumnText.showTextAligned(content, Element.ALIGN_CENTER, p, 100f,100f, 0);
  141. content.restoreState();
  142. }
  143. // public String generatePdfImage(Integer userId, String pdfUrl, boolean force) throws IOException {
  144. // String pdfFile = pdfUrl.replace(webUrl, localPath);
  145. // String dest = pdfFile.replace(".pdf", String.format("_%d.pdf", userId));
  146. // File file = new File(dest);
  147. //
  148. // if (!force && file.exists()){
  149. // return dest;
  150. // }
  151. //
  152. // PdfDocument pdf = new PdfDocument();
  153. // pdf.loadFromFile(pdfFile);
  154. //
  155. // File srcImgFile = new File(water);
  156. // Image srcImg = ImageIO.read(srcImgFile);
  157. //
  158. // BufferedImage bi = toBufferedImage(srcImg);
  159. // for (Object page: pdf.getPages()) {
  160. // AddImageWatermark((PdfPageBase)page, bi);
  161. // }
  162. //
  163. // //保存
  164. // pdf.saveToFile(dest);
  165. // //关闭
  166. // pdf.close();
  167. // return dest;
  168. // }
  169. // /**
  170. // * @param page
  171. // * 要添加水印的页面
  172. // * @param image
  173. // * 水印图片路径
  174. // */
  175. // static void AddImageWatermark(PdfPageBase page, BufferedImage image)
  176. // {
  177. // page.setBackgroundImage(image);
  178. // Rectangle2D rect = new Rectangle2D.Float();
  179. // rect.setFrame(page.getClientSize().getWidth()/2 - image.getWidth() / 2, page.getClientSize().getHeight()/2 - image.getHeight()/2, image.getWidth(), image.getHeight());
  180. // page.setBackgroundRegion(rect);
  181. // }
  182. //
  183. // /**
  184. // * @param page
  185. // * 要添加水印的页面
  186. // * @param textWatermark
  187. // * 水印文字
  188. // */
  189. // static void AddTextWatermark(PdfPageBase page, String textWatermark)
  190. // {
  191. // Dimension2D dimension2D = new Dimension();
  192. // dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 2, page.getCanvas().getClientSize().getHeight() / 3);
  193. // PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
  194. // brush.getGraphics().setTransparency(0.3F);
  195. // brush.getGraphics().save();
  196. // brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2);
  197. // brush.getGraphics().rotateTransform(-45);
  198. // brush.getGraphics().drawString(textWatermark, new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,30),true), PdfBrushes.getRed(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
  199. // brush.getGraphics().restore();
  200. // brush.getGraphics().setTransparency(1);
  201. // Rectangle2D loRect = new Rectangle2D.Float();
  202. // loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize());
  203. // page.getCanvas().drawRectangle(brush, loRect);
  204. // }
  205. }