我在 Android 应用程序中工作,我想生成并打印 PDF。但是我遇到了一些麻烦。我需要生成 宽度
为 80mm 的 PDF
,高度
可能会有所不同。
我正在尝试这个:
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);
}
}
此代码生成 PDF
,但具有 letter size
。
我在 Android Developers media size documentation 中看到“ISO_C7”媒体大小是我几乎想要的大小,但我可以更改所有“printAttrs”并且 PDF 的最终结果没有任何变化。
是否有更好的方法来生成和打印 PDF
?如何生成 80 毫米 宽度
的 PDF
?
应用的这一部分是由一位老员工制作的。
谢谢。
最佳答案
为了不让您像我一样为此伤透脑筋,请查看此错误报告: https://code.google.com/p/android/issues/detail?id=180405
考虑到这个错误报告,我认为这是 android 打印界面的问题,你不能使用 PrintAttributes 设置任何默认值,至少在 android N 之前是这样。
如果您找到/找到解决方法,请告诉我:)
关于android - 在 Android 中生成并打印具有特定大小的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31884342/