在Android中生成并打印特定大小的PDF

Hen*_*ulo 5 pdf android android-print-framework

我正在使用Android应用程序,并且想生成和打印PDF。但是我遇到了麻烦。我需要生成PDF80mm的width,并且height可能会有所不同。

我正在尝试:

public class PDFGenerator implements Runnable {
    private Context ctx;
    private View view;
    private Intent mShareIntent;
    private OutputStream os;

    public PDFGenerator(Context ctx, View view) {
        this.ctx = ctx;
        this.view = view;
        makeAndSharePDF();
    }

    public void makeAndSharePDF() {
        new Thread(this).start();
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void run() {
        PrintAttributes printAttrs = new PrintAttributes.Builder().
                setColorMode(PrintAttributes.COLOR_MODE_MONOCHROME).
                setMediaSize(PrintAttributes.MediaSize.ISO_C7).
                setResolution(new PrintAttributes.Resolution("zooey", ctx.PRINT_SERVICE, 500, 500)).
                setMinMargins(PrintAttributes.Margins.NO_MARGINS).
                build();

        PdfDocument document = new PrintedPdfDocument(ctx, printAttrs);
        PdfDocument.PageInfo pageInfo = new  PdfDocument.PageInfo.Builder(view.getWidth(), view.getHeight(), 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);
        view.draw(page.getCanvas());
        document.finishPage(page);

        try {
            File pdfDirPath = new File(ctx.getFilesDir(), "pdfs");
            pdfDirPath.mkdirs();
            File file = new File(pdfDirPath, "danfe.pdf");
            Uri contentUri = FileProvider.getUriForFile(ctx, "br.com.rdscodes.nfcelular", file);
            os = new FileOutputStream(file);
            document.writeTo(os);
            document.close();
            os.close();
            shareDocument(contentUri);
        } catch (IOException e) {
            throw new RuntimeException("Error generating file", e);
        }
    }

    private void shareDocument(Uri uri) {
        mShareIntent = new Intent();
        mShareIntent.setAction(Intent.ACTION_SEND);
        mShareIntent.setType("application/pdf");
        mShareIntent.putExtra(Intent.EXTRA_SUBJECT, "NFC-e");
        mShareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        ctx.startActivity(mShareIntent);
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码生成PDF,但带有letter size

我在Android Developers媒体尺寸文档中看到“ ISO_C7”媒体尺寸是我几乎想要的尺寸,但是我可以更改所有的“ printAttrs”,而PDF的最终结果没有任何变化。

是否有更好的方法来生成和打印清单PDF?我该如何生成PDF80毫米的width

该应用程序的这一部分是由一位老员工制作的。

谢谢。

小智 2

为了避免像我一样为此而伤脑筋,请查看此错误报告: https://code.google.com/p/android/issues/detail ?id=180405

考虑到这个错误报告,我想说这是 android 打印接口的问题,你不能真正使用 PrintAttributes 设置任何默认值,至少在 android N 之前不能。

如果您找到解决方法,请告诉我:)