PDF相关操作

PDF相关操作

  1. word转pdf

        public static void wordConvertPdf(File targetFile, File file) throws Exception {
            FileOutputStream os = new FileOutputStream(file);
    		// Address是将要被转化的word文档
            Document doc = new Document(targetFile.getAbsolutePath()); 
            DocumentBuilder builder = new DocumentBuilder(doc);
            //文档主体内容设置段后和行距
            builder.moveToDocumentStart();
            builder.getParagraphFormat().setLeftIndent(12);
            builder.getParagraphFormat().setSpaceAfter(0);
            builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
            builder.getParagraphFormat().setLineSpacing(12);
            builder.getParagraphFormat().setSpaceAfter(0);
            builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
            builder.getParagraphFormat().setLineSpacing(12);
            builder.getParagraphFormat().setSpaceAfter(0);
            builder.moveToDocumentStart();
            doc.save(os, SaveFormat.PDF);
            os.close();
        }
    
  2. 添加图片

       private String issuedAndStamped(File file) throws Exception {
            String fileUrl = null;
            String baseUrl = Constants.docXmlTemplatePath;
            PDDocument document = null;
    
            try {
                // 加载PDF文档
                document = PDDocument.load(file);
    
                // 加载图片
                PDImageXObject logo = PDImageXObject.createFromFile(path + "logo_fsda.jpg", document);
    
                Map<String, Integer> logoMap = getImageScale(logo, 60f);
                //首页插入图片
                // 获取第一页
                PDPage firstPage = document.getPage(0);
                // 在第一页的合适位置插入图片
                PDPageContentStream contentStream = new PDPageContentStream(document, firstPage, PDPageContentStream.AppendMode.APPEND, true, true);
         		contentStream.close();
    
    
                Map<String, Double> signMap = new HashMap<>();
                PDFTextStripper stripper = new PDFTextStripper() {
                    @Override
                    protected void writeString(String string, List<TextPosition> textPositions) throws IOException {
                        //System.out.println("新的一页。。。。。。");
                        if (string.contains("编制:")||string.contains("编制:")) {
                            boolean b = false;
                            for (TextPosition text : textPositions) {
                                String textValue = text.getUnicode();
                                if (Objects.equals("制", textValue)) {
                                    b = true;
                                }
                                if ((Objects.equals(":", textValue) || Objects.equals(":", textValue)) && b) {
                                    Rectangle2D.Float boundingBox = calculateBoundingBox(text);
                                    //System.out.println("Text: " + textValue);
                                    //System.out.println("(编制)Position: x=" + boundingBox.getX() + ", y=" + boundingBox.getY());
                                    signMap.put("bzrx", boundingBox.getX());
                                    signMap.put("bzry", boundingBox.getY());
                                    break;
                                }
    
                            }
                        }
                    }
                };
    
                stripper.setSortByPosition(true);
                Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
                // 遍历每一页
                for (PDPage page : document.getPages()) {
                    // 创建内容流
                    contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
                    // 在页面上绘制图片
                    contentStream.drawImage(logo, 500, 775, logoMap.get("scaledWidth"), logoMap.get("scaledHeight"));
                    // 关闭内容流
                    contentStream.close();
                }
                // 保存PDF文档
                fileUrl = baseUrl + new Date().getTime() + ".pdf";
                File f = new File(fileUrl);
                if (!f.getParentFile().exists()) {
                    f.getParentFile().mkdirs();
                }
                document.save(fileUrl);
    
                // 关闭文档
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return fileUrl;
        }
    	private static Rectangle2D.Float calculateBoundingBox(TextPosition text) {
            float x = text.getXDirAdj();
            float y = text.getYDirAdj();
            float width = text.getWidthDirAdj();
            float height = text.getHeightDir();
            return new Rectangle2D.Float(x, y, width, height);
        }
    
        private static Map<String, Integer> getImageScale(PDImageXObject image, float v) {
            // 获取图片原始的宽度和高度
            int originalWidth = image.getWidth();
            int originalHeight = image.getHeight();
    
            // 计算缩放比例
            float scaleX = v / originalWidth;
            float scaleY = v / originalHeight;
            float scale = Math.min(scaleX, scaleY);
    
            // 计算缩放后的宽度和高度
            int scaledWidth = Math.round(originalWidth * scale);
            int scaledHeight = Math.round(originalHeight * scale);
            Map<String, Integer> map = new HashMap<>();
            map.put("scaledWidth", scaledWidth);
            map.put("scaledHeight", scaledHeight);
            return map;
        }
    
    
  3. 添加水印

        private void waterMark(String inputPdfPath, String outputPdfPath) {
            try {
                String watermarkText = "FSDA";
                int interval = -5;
                PdfReader reader = new PdfReader(inputPdfPath);
                System.out.println("读取PDF文件模板完了=============================");
                PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPdfPath));
    
                BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    
                com.itextpdf.text.Rectangle pageRect = null;
                PdfGState gs = new PdfGState();
                gs.setFillOpacity(0.07f);  //透明度
                gs.setStrokeOpacity(0.07f);
                int total = reader.getNumberOfPages() + 1;
    
                JLabel label = new JLabel();
                FontMetrics metrics;
                int textH = 0;
                int textW = 0;
                label.setText(watermarkText);
                metrics = label.getFontMetrics(label.getFont());
                textH = metrics.getHeight();
                textW = metrics.stringWidth(label.getText());
    
                PdfContentByte under;
                for (int i = 1; i < total; i++) {
                    pageRect = reader.getPageSizeWithRotation(i);
                    under = stamper.getOverContent(i);
                    under.saveState();
                    under.setGState(gs);
                    under.beginText();
                    under.setFontAndSize(base, 10);
                    under.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
                    //你可以随心所欲的改你自己想要的角度   水印文字成30度角倾斜
                    for (int height = interval*2 + textH; height < pageRect.getHeight(); height = height + textH * 8) {
                        for (int width = interval + textW; width < pageRect.getWidth() + textW; width = (int) (width + (textW * 4))) {
                            under.showTextAligned(Element.ALIGN_LEFT, watermarkText, width - textW, height - textH, 20);
                        }
                    }
    
                    // 添加水印文字
                    under.endText();
                }
                System.out.println("PDF文件水印打印成功!路径:" + outputPdfPath);
                //说三遍
                //一定不要忘记关闭流
                //一定不要忘记关闭流
                //一定不要忘记关闭流
                stamper.close();
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    

posted @ 2024-02-29 19:38  meng_zhao  阅读(5)  评论(0编辑  收藏  举报