java

create PDF by java

import java.io.IOException;

import org.apache.pdfbox.PDFToImage;
import org.apache.pdfbox.examples.pdmodel.AddImageToPDF;
import org.apache.pdfbox.examples.pdmodel.AddMessageToEachPage;
import org.apache.pdfbox.exceptions.COSVisitorException;
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.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

public class PDFUtils {

public void creatblankPagepdf()
{
try {
PDDocument document = new PDDocument();

PDPage blankPage = new PDPage();
document.addPage( blankPage );
document.save(“/home/admin/BlankPage.pdf”);
document.close();

} catch (COSVisitorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {

e.printStackTrace();
}

}

public void creatHelloWorldpdf()
{
try {

PDDocument document = new PDDocument();

PDPage page = new PDPage();
document.addPage( page );

PDFont font = PDType1Font.HELVETICA_BOLD;

//Next we start a new content stream which will “hold” the to be created content:
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont( font, 12 );
contentStream.moveTextPositionByAmount( 100, 700 );
contentStream.drawString( “Hello World” );
contentStream.endText();
contentStream.close();
document.save( “/home/admin/Hello World.pdf”);
document.close();

AddImageToPDF AddImageToPDF1=new AddImageToPDF();
String inputFile=”/home/admin/Hello World.pdf”;
String OutputFile=”/home/admin/image.pdf”;
String Image=”/home/admin/raw.JPG”;
AddImageToPDF1.createPDFFromImage(inputFile,Image,OutputFile);

} catch (COSVisitorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {

e.printStackTrace();
}

}

public  static void main(String args[]){
PDFUtils pdfUtils=new PDFUtils();
//pdfUtils.creatblankPagepdf();
pdfUtils.creatHelloWorldpdf();

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s