package com.qxgmat.help; //import com.spire.pdf.PdfDocument; //import com.spire.pdf.PdfPageBase; //import com.spire.pdf.graphics.*; //import com.spire.pdf.widget.PdfPageCollection; import com.itextpdf.text.*; import com.itextpdf.text.Font; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.*; import com.qxgmat.data.dao.entity.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.awt.*; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * Created by GaoJie on 2017/11/3. */ @Service public class PdfHelp { private static final Logger logger = LoggerFactory.getLogger(PdfHelp.class); @Value("${upload.local_path}") private String localPath; @Value("${upload.web_url}") private String webUrl; @Value("${upload.offline_path}") private String offlinePath; @Value("${upload.offline_url}") private String offlineUrl; @Value("${upload.water}") private String water; private BaseFont font; private int top = 72; private int left = 93; private int size = 10; @Autowired private void getFont(@Value("${upload.font}") String path) throws IOException, DocumentException { FontFactory.registerDirectories(); String sub = ""; if (path.toLowerCase().endsWith(".ttc")){ sub += ",1"; } if (path.startsWith(".")){ // 相对路径,从resource中获取 // logger.debug("{}, {}", path, this.getClass().getClassLoader().getResource(path.replaceFirst(".",""))); // logger.debug("{}, {}", path, this.getClass().getClassLoader().getResource(path)); try { font = BaseFont.createFont(this.getClass().getClassLoader().getResource(path.replaceFirst(".","")).toString()+sub,BaseFont.IDENTITY_H,true); }catch (Exception e){ font = BaseFont.createFont(this.getClass().getClassLoader().getResource(path).toString()+sub,BaseFont.IDENTITY_H,true); } }else{ font = BaseFont.createFont(path+sub,BaseFont.IDENTITY_H,true); } } public static BufferedImage toBufferedImage(Image img) { if (img instanceof BufferedImage) { return (BufferedImage) img; } // Create a buffered image with transparency BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); // Draw the image on to the buffered image Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(img, 0, 0, null); bGr.dispose(); // Return the buffered image return bimage; } public String[] getUserWater(User user){ // 2份水印文字 String mobile = user.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})","$1****$2"); String name = (user.getRealStatus() > 0? user.getRealName().replaceAll("(.{1}).*(.{1})?","$1*$2 ") : "") + mobile; String qx = "千行ID "+String.format("%04d", user.getId()); return new String[]{name, qx}; } public String getOfflineUrl(String offline){ return offline.replace(offlinePath, offlineUrl); } public String generatePdfImage(User user, String pdfUrl, boolean force) throws IOException, DocumentException { File dir = new File(offlinePath); if (!dir.exists()) { dir.mkdirs(); } String pdfFile = pdfUrl.replace(webUrl, localPath); String dest = pdfFile.replace(".pdf", String.format("_%d.pdf", user.getId())).replace(localPath, offlinePath); File file = new File(dest); if (!force && file.exists()){ return dest; }else if(file.exists()){ file.delete(); } String[] waters = getUserWater(user); PdfReader reader = new PdfReader(pdfFile); // 如果是web项目,直接下载应该放到response的流里面 // PdfStamper stamp = new PdfStamper(reader,response.getOutputStream()); // 添加水印之后的pdf文件 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); int pageSize = reader.getNumberOfPages(); PdfContentByte under; for (int i = 1; i<=pageSize;i++){ under = stamper.getOverContent(i); Rectangle r = reader.getPageSize(i); float width = r.getWidth(); float height = r.getHeight(); 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}; for (int j = 0; j < 5; j ++){ AddTextWatermark(under, waters[0], Element.ALIGN_LEFT, left, a[j]); AddTextWatermark(under, waters[1], Element.ALIGN_CENTER, width / 2,a[j]); AddTextWatermark(under, waters[0], Element.ALIGN_RIGHT, width - left,a[j]); } } stamper.close(); reader.close(); return dest; } void AddTextWatermark(PdfContentByte content, String textWatermark, int alignment, float width, float y){ content.saveState(); // Font f = new Font(font, 10); // f.setColor(0,0,0); // f.setStyle(Font.NORMAL); PdfGState gs = new PdfGState(); gs.setFillOpacity(0.2f); content.setGState(gs); // Phrase p = new Phrase(textWatermark, f); content.beginText(); content.setColorFill(new BaseColor(0,0,0));// 文字水印 颜色 content.setFontAndSize(font, size);// 文字水印 字体及字号 // content.setTextMatrix(0, 0);// 文字水印 起始位置 content.showTextAligned(alignment, textWatermark, width, y, 0); content.endText(); // 在页面中添加多次,计算为止 // ColumnText.showTextAligned(content, Element.ALIGN_CENTER, p, 100f,100f, 0); content.restoreState(); } // public String generatePdfImage(Integer userId, String pdfUrl, boolean force) throws IOException { // String pdfFile = pdfUrl.replace(webUrl, localPath); // String dest = pdfFile.replace(".pdf", String.format("_%d.pdf", userId)); // File file = new File(dest); // // if (!force && file.exists()){ // return dest; // } // // PdfDocument pdf = new PdfDocument(); // pdf.loadFromFile(pdfFile); // // File srcImgFile = new File(water); // Image srcImg = ImageIO.read(srcImgFile); // // BufferedImage bi = toBufferedImage(srcImg); // for (Object page: pdf.getPages()) { // AddImageWatermark((PdfPageBase)page, bi); // } // // //保存 // pdf.saveToFile(dest); // //关闭 // pdf.close(); // return dest; // } // /** // * @param page // * 要添加水印的页面 // * @param image // * 水印图片路径 // */ // static void AddImageWatermark(PdfPageBase page, BufferedImage image) // { // page.setBackgroundImage(image); // Rectangle2D rect = new Rectangle2D.Float(); // rect.setFrame(page.getClientSize().getWidth()/2 - image.getWidth() / 2, page.getClientSize().getHeight()/2 - image.getHeight()/2, image.getWidth(), image.getHeight()); // page.setBackgroundRegion(rect); // } // // /** // * @param page // * 要添加水印的页面 // * @param textWatermark // * 水印文字 // */ // static void AddTextWatermark(PdfPageBase page, String textWatermark) // { // Dimension2D dimension2D = new Dimension(); // dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 2, page.getCanvas().getClientSize().getHeight() / 3); // PdfTilingBrush brush = new PdfTilingBrush(dimension2D); // brush.getGraphics().setTransparency(0.3F); // brush.getGraphics().save(); // brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2); // brush.getGraphics().rotateTransform(-45); // brush.getGraphics().drawString(textWatermark, new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,30),true), PdfBrushes.getRed(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center)); // brush.getGraphics().restore(); // brush.getGraphics().setTransparency(1); // Rectangle2D loRect = new Rectangle2D.Float(); // loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize()); // page.getCanvas().drawRectangle(brush, loRect); // } }