PDFBox Adding Multiple Lines - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
PDFBox Adding Multiple Lines

PDFBox Adding Multiple Lines

PDFBox Adding Multiple Lines

In the previous section, we discussed how to add text content to the pages of a PDF document. The previous program writes the only single line in a page. If we want to insert more than one line in the page than it will not allow and end inserting text after ending the line.
To add multiple lines in a PDF document we need to use the setLeading() method and after finishing each line we use newline() method to insert text from a new line.

import java.io.File;
import java.io.IOException;

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

public class AddMultipleLines {
   public static void main(String args[]) throws IOException {

      //Loading an existing document
      File file = new File("C:/PdfBox_Examples/my_pdf.pdf");
      PDDocument doc = document.load(file);
       
      //Creating a PDF Document
      PDPage page = doc.getPage(1);  
       
      PDPageContentStream contentStream = new PDPageContentStream(doc, page); 
       
      //Begin the Content stream 
      contentStream.beginText(); 
       
      //Setting the font to the Content stream
      contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );
       
      //Setting the leading
      contentStream.setLeading(14.5f);

      //Setting the position for the line
      contentStream.newLineAtOffset(25, 725);

      String text1 = "This is an example of adding text to a page in the pdf document.
         we can add as many lines";
      String text2 = "as we want like this using the ShowText()  method of the
         ContentStream class";

      //Adding text in the form of string
      contentStream. ShowText(text1);
      contentStream.newLine();
      contentStream. ShowText(text2);
      //Ending the content stream
      contentStream.endText();

      System.out.println("Content added");

      //Closing the content stream
      contentStream.close();

      //Saving the document
      doc.save(new File("C:/PdfBox_Examples/new.pdf"));
            
      //Closing the document
      doc.close();
   }
}

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.