在传递给打印功能之前设置您的PrintAttributes 。这对我有用。
PrintManager printManager = (PrintManager) context.getSystemService(PRINT_SERVICE);
PrintAttributes newAttributes = new PrintAttributes.Builder().
setMediaSize(PrintAttributes.MediaSize.ISO_A4).
setMinMargins(PrintAttributes.Margins.NO_MARGINS).
build();
printManager.print(context.getString(R.string.print_job_name),
new PdfFragmentPrintDocumentAdapter(context, view), newAttributes);
PdfFragmentPrintDocumentAdapter.java
public class PdfFragmentPrintDocumentAdapter extends PrintDocumentAdapter {
private PrintedPdfDocument document;
private Context context;
private View view;
public PdfFragmentPrintDocumentAdapter(Context context, View view) {
this.context = context;
this.view = view;
}
@Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes,
CancellationSignal cancellationSignal,
LayoutResultCallback callback, Bundle extras) {
document = new PrintedPdfDocument(context, newAttributes);
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
PrintDocumentInfo.Builder builder = new PrintDocumentInfo
.Builder(context.getString(R.string.pdf_file_name)+".pdf")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(1);
PrintDocumentInfo info = builder.build();
callback.onLayoutFinished(info, true);
}
@Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination,
CancellationSignal cancellationSignal,
PrintDocumentAdapter.WriteResultCallback callback) {
cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
@Override
public void onCancel() {
Toast.makeText(context, context.getString(R.string.printing_cancel), Toast.LENGTH_SHORT).show();
}
});
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 {
document.writeTo(new FileOutputStream(
destination.getFileDescriptor()));
} catch (IOException e) {
String exception = e.toString();
Toast.makeText(context, context.getString(R.string.printing_failed)+"\n" + exception, Toast.LENGTH_SHORT).show();
callback.onWriteFailed(exception);
return;
} finally {
document.close();
document = null;
}
callback.onWriteFinished(new PageRange[]{new PageRange(0, 0)});
}
@Override
public void onFinish() {
super.onFinish();
}
}