1

I tried to learn how to generate PDF for my Android application.
I followed the official documentation but the code didn't work.
the compiler found me some compilation error but all I did was to copy/paste the code from the code.
please take a look at the code and tell me why (:

 PrintAttributes printAttributes = new PrintAttributes.Builder().
         setMediaSize(PrintAttributes.MediaSize.ISO_A4)
         .setColorMode(PrintAttributes.COLOR_MODE_COLOR)
         .setMinMargins(PrintAttributes.Margins.NO_MARGINS)
         .build();


PrintedPdfDocument document = new PrintedPdfDocument(this, printAttributes);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}



// crate a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create();

// start a page
PdfDocument.Page page = document.startPage(pageInfo);

// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);
// add more pages
// write the document content
document.writeTo(getOutputStream());

// close the document
document.close();
Matnako
  • 75
  • 5
  • You need wrap the PDF generation code into a method. – Allan Pereira Apr 14 '16 at 16:04
  • @AllanPereira if i wrap generation code into a method, I still have these errors : https://gyazo.com/d83aff5a0a4afddfc7a10ae85973a633 (sorry i had to screen it, because the errors were not inline..) – Matnako Apr 14 '16 at 16:12

1 Answers1

0
  1. PageInfo.Builder does not take the parameters you used. Try to replace

     PdfDocument.PageInfo pageInfo = 
             new PdfDocument.PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create();
    

    with

    PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(100,100,1).create();`
    

    Please check the documentation for PdfDocument.PageInfo.Builder

  2. getContentView() is not called from the right class, please check here

  3. getOutputStream() does not exist for the Activity class. If what you want to do is to copy the content into a file, you should probably create a new file, and the copy the output to that file.

  4. all your code needs to be enclosed in a method and then called from the onCreate() method.

For more information about generating PDF for Android, please check [this link].3

Community
  • 1
  • 1