I have written an android app to do inspections. It collects the data and then formats it and places it on a PDF document. I am having a problem creating a 2nd page of the PDF before I save it and email it. I have commented out "PAGE 2 OF PDF". This section of code up to the declaration of pdfName is where the problem is. I do not want to use anything like iText or Apose. Can anyone help???
public void createPDF(){
// Create a object of PdfDocument
PdfDocument document = new PdfDocument();
// content view is TableLayout of data
View content = findViewById(id.final_table_layout_for_pdf_page_1);
// create a page info with attributes as below
// page number, height and width
// i have used height and width to that of pdf content view
int pageNumber = 1;
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(content.getWidth(),
content.getHeight() - 20, pageNumber).create();
// create a new page from the PageInfo
PdfDocument.Page page = document.startPage(pageInfo);
// repaint the user's text into the page
content.draw(page.getCanvas());
// do final processing of the page
document.finishPage(page);
/* PAGE 2 OF PDF
content = findViewById(id.final_table_layout_for_pdf_page_2);
// create a page info with attributes as below
// for 2nd page
// i have used height and width to that of pdf content view
pageNumber = 2;
pageInfo = new PdfDocument.PageInfo.Builder(content.getWidth(),
content.getHeight() - 20, pageNumber).create();
// create a new page from the PageInfo
page = document.startPage(pageInfo);
// repaint the user's text into the page
content.draw(page.getCanvas());
// do final processing of the page
document.finishPage(page);*/
// saving pdf document to root dir
String pdfName = "pdf_inspection_demo.pdf";
// all created files will be saved at path /sdcard/PDFDemo_AndroidSRC/
File outputFile = new File("/storage/emulated/0/", pdfName);
try {
outputFile.createNewFile();
OutputStream out = new FileOutputStream(outputFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
errorString = e.getMessage();
}
}
private void generatePDF() {
PdfDocument pdfDocument = new PdfDocument();
criNewPag(1,"ان شاء الله ",pdfDocument);
criNewPag(2,"ان شاء الله ربي ",pdfDocument);
File file = new File(Environment.getExternalStorageDirectory(), "GFG.pdf");
try {
pdfDocument.writeTo(new FileOutputStream(file));
Toast.makeText(getApplicationContext(), "PDF file generated successfully.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
pdfDocument.close();
}
private void criNewPag(int numpag,String text, PdfDocument pdfDocument ){
Paint paint = new Paint();
Paint title = new Paint();
PdfDocument.PageInfo mypageInfo = new PdfDocument.PageInfo.Builder(pagewidth, pageHeight, numpag).create();
PdfDocument.Page myPage = pdfDocument.startPage(mypageInfo);
Canvas canvas = myPage.getCanvas();
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.gfgimage);
scaledbmp = Bitmap.createScaledBitmap(bmp, 140, 140, false);
canvas.drawBitmap(scaledbmp, 56, 40, paint);
title.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
title.setTextSize(15);
title.setColor(ContextCompat.getColor(this, R.color.purple_200));
canvas.drawText("A portal for IT professionals.", 209, 100, title);
canvas.drawText("Geeks for Geeks", 209, 80, title);
title.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
title.setColor(ContextCompat.getColor(this, R.color.purple_200));
title.setTextSize(15);
title.setTextAlign(Paint.Align.CENTER);
canvas.drawText(text, 150, 240, title);
pdfDocument.finishPage(myPage);
}
Related
I want to export data to a PDF. As a test I first want to print just a TextView. This is my code:
public static void exportPdf (Context ctx) {
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(1240, 1754, 1).create();
// start a page
PdfDocument.Page page = document.startPage(pageInfo);
// draw something on the page
LinearLayout content = new LinearLayout(ctx);
int measureWidth = View.MeasureSpec.makeMeasureSpec(page.getCanvas().getWidth(), View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(page.getCanvas().getHeight(), View.MeasureSpec.EXACTLY);
content.measure(measureWidth, measuredHeight);
content.layout(0, 0, page.getCanvas().getWidth(), page.getCanvas().getHeight());
TextView tv = new TextView(content.getContext());
tv.setText("Test");
content.addView(tv);
content.draw(page.getCanvas());
// finish the page
document.finishPage(page);
// write the document content
...
}
The result is an empty page. What am I doing wrong?
Edit: It is not my goal to write a text on the pdf's canvas. I want to display a Layout. The TextView is just provisory.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I was trying to create a PDF using iText.
My objective is to make a question paper. I was able to only add the questions and answers to the PDF.
Then i tried modifying it by adding page numbers, watermarks etc. by adding Header/Footer. Now it gives me NullPointerException i cannot figure out what went wrong.
Error I'm getting
Caused by: java.lang.NullPointerException
at
edu.ijse.gdse41.ams.other.HeaderFooter.onEndPage(HeaderFooter.java:57)
at com.itextpdf.text.pdf.PdfDocument.newPage(PdfDocument.java:902)
at com.itextpdf.text.pdf.PdfDocument.close(PdfDocument.java:837) at
com.itextpdf.text.Document.close(Document.java:416) at
edu.ijse.gdse41.ams.view.CreateAssignmentController.createPDF(CreateAssignmentController.java:644)
at
edu.ijse.gdse41.ams.view.CreateAssignmentController.proceedBtnClicked(CreateAssignmentController.java:292)
... 58 more
createPDF() method in CreateAssignment.java class
private void createPDF(ArrayList<Assignment_QuesDTO> questionPaper) throws DocumentException, BadElementException, IOException {
try {
OutputStream outputStream = null;
Document doc = new Document();
outputStream = new FileOutputStream(new File("C:\\Users\\Dell\\Documents\\NetBeansProjects\\AssignmentManagementSystem\\src\\PDF\\mypdf.pdf"));
PdfWriter writer = PdfWriter.getInstance(doc, outputStream);
PdfPageEventHelper eventHelper = new HeaderFooter(doc);
writer.setPageEvent(eventHelper);
doc.open();
Font fontTitle = new Font(Font.getFamily("TIMES_ROMAN"), 15);
Paragraph title = new Paragraph("ABC", fontTitle);
title.setAlignment(Paragraph.ALIGN_CENTER);
doc.add(title);
for (int i = 0; i < 3; i++) {
doc.add(Chunk.NEWLINE);
}
Paragraph subTitle = new Paragraph(questionPaper.get(1).getAssignment().getAssignName());
subTitle.setAlignment(Paragraph.ALIGN_CENTER);
Paragraph subTitle2 = new Paragraph(questionPaper.get(1).getAssignment().getDate());
subTitle2.setAlignment(Paragraph.ALIGN_CENTER);
doc.add(subTitle);
doc.add(subTitle2);
List orderedList = new List(List.ORDERED);
for (Assignment_QuesDTO questionPaper1 : questionPaper) {
Paragraph question = new Paragraph(questionPaper1.getQuestion().getQues());
question.setAlignment(Paragraph.ALIGN_JUSTIFIED);
orderedList.add(question);
List desc = new List(List.UNORDERED);
desc.setIndentationLeft(36);
desc.setListSymbol(new Chunk(" "));
desc.add(new Phrase("\t\t" + questionPaper1.getQuestion().getQuesDesc()));
orderedList.add(desc);
orderedList.add(Chunk.NEWLINE);
List answers = new List(List.ORDERED,List.ALPHABETICAL);
answers.setIndentationLeft(72);
for (AnswerDTO answer : questionPaper1.getQuestion().getAnswers()) {
answers.add(" " + answer.getAnswer());
}
orderedList.add(answers);
orderedList.add(Chunk.NEWLINE);
}
doc.add(orderedList);
doc.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(CreateAssignmentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
HeaderFooter.java class
public class HeaderFooter extends PdfPageEventHelper {
Phrase[] header = new Phrase[2];
int pageNum;
Image watermark;
public HeaderFooter(Document doc) throws BadElementException, IOException {
this.watermark = Image.getInstance("C:\\Users\\Dell\\Documents\\NetBeansProjects\\AssignmentManagementSystem\\src\\edu\\ijse\\gdse41\\ams\\resources\\images\\watermark.png");
watermark.rotate();
watermark.scaleToFit(doc.getPageSize());
watermark.setRotationDegrees(30);
}
#Override
public void onChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) {
header[1] = new Phrase(title.getContent());
pageNum = 1;
}
#Override
public void onEndPage(PdfWriter writer, Document document) {
try {
Rectangle rect = writer.getBoxSize("art");
switch (writer.getPageNumber() % 2) {
case 0:
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, header[0], rect.getRight(), rect.getTop(), 0);
break;
case 1:
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, header[1], rect.getLeft(), rect.getTop(), 0);
break;
}
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(String.format("Page %d", pageNum)), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
PdfContentByte content = writer.getDirectContent();
content.addImage(watermark);
} catch (DocumentException ex) {
Logger.getLogger(HeaderFooter.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void onStartPage(PdfWriter writer, Document document) {
pageNum++;
}
#Override
public void onOpenDocument(PdfWriter writer, Document document) {
header[0] = new Phrase("ABC");
}
}
In your page event, you assume that the PDF you are creating has an /ArtBox boundary:
Rectangle rect = writer.getBoxSize("art");
However, when I look at the code that creates your PDF, I don't see you creating such a page boundary anywhere. This means that rect is null, and that methods such as rect.getRight(), rect.getTop(),... throw a NullPointerException.
I'm using PDFBox 2. Trying to write a PNG image file to new PDF file.
I saw there was already an answer that mention it was fixed on PDFBox2:
How to add .png images to pdf using Apache PDFBox and
https://issues.apache.org/jira/browse/PDFBOX-1990
This is my code:
package pdfProj;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
public class b {
public static void main(String[] args) {
PDDocument doc = null;
doc = new PDDocument();
doc.addPage(new PDPage());
try{
BufferedImage awtImage = ImageIO.read( new File( "c://temp//line_chart.png" ) );
PDImageXObject pdImageXObject = LosslessFactory.createFromImage(doc, awtImage);
PDPageContentStream contentStream = new PDPageContentStream(doc, new PDPage(), true, false);
contentStream.drawImage(pdImageXObject, 200, 300, awtImage.getWidth() / 2, awtImage.getHeight() / 2);
contentStream.close();
doc.save( "c://temp//pdf//PDF_image.pdf" );
doc.close();
} catch (Exception io){
System.out.println(" -- fail --" + io);
}
}
}
There is no exception. Just getting an empty PDF file created.
The issue is that you add a new page to the document
doc.addPage(new PDPage());
but then create a content stream for yet another new page which you don't add to the document:
PDPageContentStream contentStream = new PDPageContentStream(doc, new PDPage(), true, false);
You should create the content stream for the page you added to the document, e.g. like this:
PDDocument doc = null;
doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
try{
BufferedImage awtImage = ImageIO.read( new File( "c://temp//line_chart.png" ) );
PDImageXObject pdImageXObject = LosslessFactory.createFromImage(doc, awtImage);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
contentStream.drawImage(pdImageXObject, 200, 300, awtImage.getWidth() / 2, awtImage.getHeight() / 2);
contentStream.close();
doc.save( "c://temp//pdf//PDF_image.pdf" );
doc.close();
} catch (Exception io){
System.out.println(" -- fail --" + io);
}
I have an app that calculate time of phone usage and you can share it on social networks, instead of normal gettext() I want to put the results on an image and save it to phone. How can I create an image that I can save to the phone that includes custom text?
What you want to do is to paint to a Canvas that's linked to a Bitmap, and save the bitmap. Here's a few bits of code that you should be able to string together to make it work. Note that you'll have to still add the paining to the canvas, in the getBitmap() function.
private Bitmap getBitmap() {
Bitmap bitmap = Bitmap.createBitmap(mPieToss.getWidth(),
mPieToss.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// Draw things to your canvas. They will be included as your BitMap, which is saved later on
return bitmap;
}
public void save() {
Bitmap bitmap = getBitmap();
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String filename = "Imagen_" + timestamp + ".jpg";
File file = new File(path, filename);
FileOutputStream stream;
// This can fail if the external storage is mounted via USB
try {
stream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mUri = Uri.fromFile(file);
bitmap.recycle();
}
First of all convert your layout to bitmap:
View contentLayout; // your layout with bavkground image and TextView
Bitmap bitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
content.draw(canvas);
Now you can save it to the file:
FileOutputStream fos = new FileOutputStream(fileName, false);
bitmap.compress(Bitmap.CompressFormat.PNG, 75, fos);
fos.flush();
fos.close();
I generate an event for adding header and footer to every page on my pdf document, the problem is that when I add a new image to the page, the new image appears under the header image. I had tried to find the solution, but I can´t find it, I have tried with image on png with Alpha channel set, but the problem don´t disappear.
class PieCabecera extends PdfPageEventHelper{
public int numeroPagina;
public Image imagen;
public PdfPTable tabla;
public PdfTemplate tpl;
public Phrase cabecera;
Font smallBold = new Font(Font.FontFamily.HELVETICA, 1, Font.BOLD);
/**
*
* #param writer
* #param documento
*/
#Override
public void onStartPage(PdfWriter writer, Document documento){
numeroPagina++;
try{
imagen = Image.getInstance("D:/Users/Operador/Documents/NetBeansProjects/ServiciosWeb-dev/web/img/logoPDF.jpg");
imagen.setAbsolutePosition(50, 0);
PdfContentByte cbCabecera = writer.getDirectContent();
tpl = cbCabecera.createTemplate(600, 250);
tpl.addImage(imagen);
cbCabecera.addTemplate(tpl, 0, 750);
cabecera = new Phrase(cbCabecera + ".", smallBold);
documento.add(cabecera);
Paragraph parrafo0 = new Paragraph();
parrafo0.setSpacingBefore(12);
parrafo0.setSpacingAfter(14);
documento.add(parrafo0);
/*Línea de separación*/
LineSeparator ls = new LineSeparator();
documento.add(new Chunk(ls));
Paragraph parrafo = new Paragraph();
parrafo.setSpacingBefore(4);
documento.add(parrafo);
}catch(BadElementException e){
LOGGER.log(Level.SEVERE, "Error: {0}", e.getStackTrace());
}catch( IOException e){
LOGGER.log(Level.SEVERE, "Error: {0}", e.getStackTrace());
}catch( DocumentException e){
LOGGER.log(Level.SEVERE, "Error: {0}", e.getStackTrace());
}
}
/**
*
* #param writer
* #param documento
*/
#Override
public void onEndPage(PdfWriter writer, Document documento){
Rectangle rect = writer.getBoxSize("art");
//header
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER, cabecera, rect.getRight(), rect.getTop(), 0);
//footer
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(String.format("Página %d", numeroPagina)), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
}
}
Thanks in advance for your help.
Have you set the margins of the Document so that you take into account the height of both header and footer?