Android: PdfDocument generates empty pdf

前端 未结 4 1529
无人及你
无人及你 2020-12-14 19:20
        PdfDocument document = new PdfDocument();
        // crate a page description
        PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create();
                


        
4条回答
  •  情话喂你
    2020-12-14 19:57

    The example that has helped me the most is the one that it can be found in the Android Cookbook You can find the corresponding code in their github account.

    Mix that code with the one for writing and you will have it:

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void run() {
        // Create a shiny new (but blank) PDF document in memory
        // We want it to optionally be printable, so add PrintAttributes
        // and use a PrintedPdfDocument. Simpler: new PdfDocument().
        PrintAttributes printAttrs = new PrintAttributes.Builder().
                setColorMode(PrintAttributes.COLOR_MODE_COLOR).
                setMediaSize(PrintAttributes.MediaSize.NA_LETTER).
                setResolution(new PrintAttributes.Resolution("zooey", PRINT_SERVICE, 300, 300)).
                setMinMargins(PrintAttributes.Margins.NO_MARGINS).
                build();
        PdfDocument document = new PrintedPdfDocument(this, printAttrs);
        // crate a page description
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(300, 300, 1).create();
        // create a new page from the PageInfo
        PdfDocument.Page page = document.startPage(pageInfo);
        // repaint the user's text into the page
        View content = findViewById(R.id.textArea);
        content.draw(page.getCanvas());
        // do final processing of the page
        document.finishPage(page);
        // Here you could add more pages in a longer doc app, but you'd have
        // to handle page-breaking yourself in e.g., write your own word processor...
        // Now write the PDF document to a file; it actually needs to be a file
        // since the Share mechanism can't accept a byte[]. though it can
        // accept a String/CharSequence. Meh.
        try {
            File f = new File(Environment.getExternalStorageDirectory().getPath() + "/pruebaAppModerator.pdf");
            FileOutputStream fos = new FileOutputStream(f);
            document.writeTo(fos);
            document.close();
            fos.close();            
        } catch (IOException e) {
            throw new RuntimeException("Error generating file", e);
        }
    }
    

提交回复
热议问题