rakchouh 0 Newbie Poster

Hi,
I am writing the content of a long text file in pdf using PDFbox API in java but only half the page I am able to write please assit me with it asap here is my code:

import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.PDFont;

class WriteToPDF{

public WriteToPDF()
{

    resultArea();
}

public void resultArea()
{
        try
           {    PDDocument doc = null;
                 PDPage page = null;
                 BufferedReader fr1 = new BufferedReader(new FileReader("test.txt"));
                 BufferedReader fr2 = new BufferedReader(new FileReader("test2.txt"));
                          doc = new PDDocument();

                  page = new PDPage();

                  doc.addPage(page);
                  PDFont font = PDType1Font.HELVETICA;

                  PDPageContentStream content = new PDPageContentStream(doc, page, true, true);



            int xpos=20, ypos=760 ;

                     String res1, res2;
                 while((res1=fr1.readLine()) != null  )
                  {     content.beginText();            
                res2=fr2.readLine();
                if(res1.equals(res2))
                {


                          content.moveTextPositionByAmount( xpos,ypos );
                          content.drawString(res1);
                      ypos = ypos - 8;

                }
                else 
                {

                          content.moveTextPositionByAmount( xpos,ypos );
                          content.drawString(res2); 
                       ypos = ypos - 8;


                }
                content.endText();
                  }


                  content.close();
                 doc.save("PDFWithText.pdf");
                 doc.close();

                fr1.close();fr2.close();
               }
        catch(FileNotFoundException e)
            {
                System.out.println("File does not exist. " + e);
         }
      catch(Exception e)
       {
              System.out.println("Some I/O problem. " + e);
        }

}

public static void main(String args[])
  {
        WriteToPDF tsf = new WriteToPDF();

  }
}

Dani AI

Generated

— the symptom (text stops half-way down) and a quick look at your loop point to two separate issues: page/line management and a risky file-compare pattern that can throw a NullPointerException.

Key fixes and checklist

  • Stop writing forever on a single PDPage. Compute available height (page height minus top/bottom margins) and the line height (font size * leading). When the next line would go below the bottom margin, finish the current text block, close the content stream, add a new PDPage, and begin a new text block at the top of that new page.
  • Don’t call equals on a possibly-null second-file line. If fr2.readLine() returns null while fr1 still has lines, res1.equals(res2) will throw. Check for null before comparing or use Objects.equals(res1,res2).
  • Begin a text block once per page (call beginText()), use setLeading() and newLine() (or newLineAtOffset) to move between lines, and call endText() only when the page is done. Opening/closing text for every line is inefficient and can lead to positioning mistakes.
  • Long physical lines need wrapping. Measure text width using the PDFont metrics (font.getStringWidth(...)/1000 * fontSize) and break lines to fit the page width.
  • Use try-with-resources to ensure files, streams and the PDDocument are closed.

Minimal pattern (PDFBox 2.x)

try (PDDocument doc = new PDDocument();
     BufferedReader in = new BufferedReader(new FileReader("test.txt"))) {
  PDPage page = new PDPage();
  doc.addPage(page);
  try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
    cs.beginText();
    cs.setFont(PDType1Font.HELVETICA, 12);
    cs.setLeading(14f);
    cs.newLineAtOffset(marginLeft, startY);
    for (String line; (line = in.readLine()) != null; ) {
      // wrap line to page width if needed
      cs.showText(line);
      cs.newLine();
      // when y < bottom -> cs.endText(), cs.close(), add new page and continue
    }
    cs.endText();
  }
  doc.save("out.pdf");
}

See the official PDFBox docs for API details and migration notes: PDFBox documentation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.