如何在PDFBox中将字符串保存为PDF?

问题描述 投票:0回答:2

我目前正在使用 PDFBox 创建一个 PDF,其中必要的位置都填充了正确的信息。我的项目中有我的字符串,但由于某种原因,我无法使用

doc.save();
功能将该字符串放入 pdf 文件中。

有什么办法可以做到这样的事情,或者我应该以不同的方式解决这个问题吗?

public static void main(String[] args) {
        String fileName = "testPDF.pdf";
        
        try{
            PDDocument doc = PDDocument.load(new File("sample.pdf"));
            String text = new PDFTextStripper().getText(doc);

            String name = text.replace("nameReplace", "Example Ethan");
            
            doc.save(fileName);
            doc.close();

        }
        catch(IOException e){
            System.out.println(e.getMessage());
        }
    }
java string pdf replace pdfbox
2个回答
0
投票

如果我理解正确的话,您想编辑PDF中的一句话

   PDDocument doc = PDDocument.load(file);
              stripper = new PDFTextStripper();
                
              String text = stripper.getText(doc);
              Pattern pattern = Pattern.compile("\\bluca\\b");
              Matcher matcher = pattern.matcher(text);
                

     matcher.find();
                  String group = matcher.group();
                  int start = matcher.start();
                  int end = matcher.end();
        String hj=  matcher.    replaceFirst("Carlone");
              System.out.println(group + " " + start + " " + end+hj);

         

0
投票

试试这个

public static void main(String[] args) {
        String fileName = "testPDF.pdf";
        
        try {
            PDDocument doc = PDDocument.load(new File("sample.pdf"));
            String text = new PDFTextStripper().getText(doc);

            // Assuming the text you want to replace is on the first page
            PDPage page = doc.getPage(0);
            
            if (text.contains("nameReplace")) {
                // Remove the content of the first page
                page.setContents(null);
                
                try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true)) {
                    // Here you would ideally re-add all the previous content (this example won't cover that)
                    
                    // Add replaced text (for simplicity, this example assumes the text fits in the given position)
                    contentStream.beginText();
                    contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
                    contentStream.newLineAtOffset(100, 700);
                    contentStream.showText(text.replace("nameReplace", "Example Ethan"));
                    contentStream.endText();
                }
            }

            doc.save(fileName);
            doc.close();

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.