0 Replies Latest reply: Oct 19, 2011 6:22 AM by 895234 RSS

    How to replace string in existing pdf using pdfbox?

    895234
      My requirement:

      Your loan amount @loanamount is approved.

      I wanted to replace @loanamount to 5,00,000. If i try with pdfbox api,i am not able to replace. i am getting empty space in pdf.
      If i use same api and if try to replace @loanamount to abcd. now its replacing

      replaceFirst("@loanamount","5,00,00"); - not able to replace. getting empty content in pdf

      public void replaceString()
      {  
      PDDocument doc = null;
      try {     
      doc = PDDocument.load("D:/DOCS/Letter.pdf"); //Input PDF File Name
      List pages = doc.getDocumentCatalog().getAllPages();
      for (int i = 0; i < pages.size(); i++)
      {     
      PDPage page = (PDPage) pages.get(i);
      PDStream contents = page.getContents();
      PDFStreamParser parser = new PDFStreamParser(contents.getStream());
      parser.parse();
      List tokens = parser.getTokens();
      for (int j = 0; j < tokens.size(); j++)
      {     
      Object next = tokens.get(j);
      if (next instanceof PDFOperator)
      {     
      PDFOperator op = (PDFOperator) next;
      // Tj and TJ are the two operators that display strings in a PDF
      if (op.getOperation().equals("Tj"))
      {     
      // Tj takes one operator and that is the string
      // to display so lets update that operator
      COSString previous = (COSString) tokens.get(j - 1);

      System.out.println("COSString::"+previous);

      String string = previous.getString();

      string = string.replaceFirst("@loanamount", "5,00,000");

      //Word you want to change. Currently this code changes word "Solr" to "Solr123"
      previous.reset();

      previous.append(string.getBytes());
      }

      PDStream updatedStream = new PDStream(doc);
      OutputStream out = updatedStream.createOutputStream();
      ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
      tokenWriter.writeTokens(tokens);

      System.out.println("updatedStream::"+updatedStream.getInputStreamAsString());
      page.setContents(updatedStream);

      //setItem(COSName.CONTENTS,updatedStream);

      }
      doc.save("D:/DOCS/loanamt_filled.pdf"); //Output file name

      sample content in pdf:
      Dear ABC,

      Your loan amount @loanamount is approved.

      Regards,
      DEF

      Output:Your loan amount is approved.
      I m getting empty spaces instead of @loanamount


      Could anyone help me out ?

      Please suggest me java open source api to replace caption or content in existing pdf.

      Thanks in advance...