PdfHelp.java 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. String pdfFile = pdfUrl.replace(webUrl, localPath);
  89. String dest = pdfFile.replace(".pdf", String.format("_%d.pdf", user.getId())).replace(localPath, offlinePath);
  90. File file = new File(dest);
  91. if (!force && file.exists()){
  92. return dest;
  93. }else if(file.exists()){
  94. file.delete();
  95. }
  96. String[] waters = getUserWater(user);
  97. PdfReader reader = new PdfReader(pdfFile);
  98. // 如果是web项目,直接下载应该放到response的流里面
  99. // PdfStamper stamp = new PdfStamper(reader,response.getOutputStream());
  100. // 添加水印之后的pdf文件
  101. PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  102. int pageSize = reader.getNumberOfPages();
  103. PdfContentByte under;
  104. for (int i = 1; i<=pageSize;i++){
  105. under = stamper.getOverContent(i);
  106. Rectangle r = reader.getPageSize(i);
  107. float width = r.getWidth();
  108. float height = r.getHeight();
  109. 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};
  110. for (int j = 0; j < 5; j ++){
  111. AddTextWatermark(under, waters[0], Element.ALIGN_LEFT, left, a[j]);
  112. AddTextWatermark(under, waters[1], Element.ALIGN_CENTER, width / 2,a[j]);
  113. AddTextWatermark(under, waters[0], Element.ALIGN_RIGHT, width - left,a[j]);
  114. }
  115. }
  116. stamper.close();
  117. reader.close();
  118. return dest;
  119. }
  120. void AddTextWatermark(PdfContentByte content, String textWatermark, int alignment, float width, float y){
  121. content.saveState();
  122. // Font f = new Font(font, 10);
  123. // f.setColor(0,0,0);
  124. // f.setStyle(Font.NORMAL);
  125. PdfGState gs = new PdfGState();
  126. gs.setFillOpacity(0.2f);
  127. content.setGState(gs);
  128. // Phrase p = new Phrase(textWatermark, f);
  129. content.beginText();
  130. content.setColorFill(new BaseColor(0,0,0));// 文字水印 颜色
  131. content.setFontAndSize(font, size);// 文字水印 字体及字号
  132. // content.setTextMatrix(0, 0);// 文字水印 起始位置
  133. content.showTextAligned(alignment, textWatermark, width, y, 0);
  134. content.endText();
  135. // 在页面中添加多次,计算为止
  136. // ColumnText.showTextAligned(content, Element.ALIGN_CENTER, p, 100f,100f, 0);
  137. content.restoreState();
  138. }
  139. // public String generatePdfImage(Integer userId, String pdfUrl, boolean force) throws IOException {
  140. // String pdfFile = pdfUrl.replace(webUrl, localPath);
  141. // String dest = pdfFile.replace(".pdf", String.format("_%d.pdf", userId));
  142. // File file = new File(dest);
  143. //
  144. // if (!force && file.exists()){
  145. // return dest;
  146. // }
  147. //
  148. // PdfDocument pdf = new PdfDocument();
  149. // pdf.loadFromFile(pdfFile);
  150. //
  151. // File srcImgFile = new File(water);
  152. // Image srcImg = ImageIO.read(srcImgFile);
  153. //
  154. // BufferedImage bi = toBufferedImage(srcImg);
  155. // for (Object page: pdf.getPages()) {
  156. // AddImageWatermark((PdfPageBase)page, bi);
  157. // }
  158. //
  159. // //保存
  160. // pdf.saveToFile(dest);
  161. // //关闭
  162. // pdf.close();
  163. // return dest;
  164. // }
  165. // /**
  166. // * @param page
  167. // * 要添加水印的页面
  168. // * @param image
  169. // * 水印图片路径
  170. // */
  171. // static void AddImageWatermark(PdfPageBase page, BufferedImage image)
  172. // {
  173. // page.setBackgroundImage(image);
  174. // Rectangle2D rect = new Rectangle2D.Float();
  175. // rect.setFrame(page.getClientSize().getWidth()/2 - image.getWidth() / 2, page.getClientSize().getHeight()/2 - image.getHeight()/2, image.getWidth(), image.getHeight());
  176. // page.setBackgroundRegion(rect);
  177. // }
  178. //
  179. // /**
  180. // * @param page
  181. // * 要添加水印的页面
  182. // * @param textWatermark
  183. // * 水印文字
  184. // */
  185. // static void AddTextWatermark(PdfPageBase page, String textWatermark)
  186. // {
  187. // Dimension2D dimension2D = new Dimension();
  188. // dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 2, page.getCanvas().getClientSize().getHeight() / 3);
  189. // PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
  190. // brush.getGraphics().setTransparency(0.3F);
  191. // brush.getGraphics().save();
  192. // brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2);
  193. // brush.getGraphics().rotateTransform(-45);
  194. // brush.getGraphics().drawString(textWatermark, new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,30),true), PdfBrushes.getRed(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
  195. // brush.getGraphics().restore();
  196. // brush.getGraphics().setTransparency(1);
  197. // Rectangle2D loRect = new Rectangle2D.Float();
  198. // loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize());
  199. // page.getCanvas().drawRectangle(brush, loRect);
  200. // }
  201. }