在Android中,使用PrintManager設置打印紙張大小和類型,你需要遵循以下步驟:
<uses-permission android:name="android.permission.PRINT" />
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
PrintDocumentInfo printDocumentInfo = new PrintDocumentInfo.Builder("My Document")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setDefaultPageSize(PageSize.A4) // 設置紙張尺寸,例如A4
.build();
PrintDocument printDocument = new PrintDocument() {
@Override
public void onWrite(PrintWriter out) throws IOException {
// 在這里繪制你的文檔內容
}
@Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, Rect bounds, Rect[] pages) {
// 在這里處理頁面布局
}
};
printManager.printDocument(printDocumentInfo, printDocument, new PrintCallback() {
@Override
public void onCompletion(PrintJobInfo printJobInfo) {
super.onCompletion(printJobInfo);
if (printJobInfo.getState() == PrintJobInfo.STATE_COMPLETED) {
Toast.makeText(getApplicationContext(), "打印完成", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "打印失敗", Toast.LENGTH_SHORT).show();
}
}
});
注意:在上述代碼中,我們使用了默認的A4紙張尺寸。你可以根據需要使用其他紙張尺寸,例如PageSize.A3
、PageSize.LEGAL
等。只需將setDefaultPageSize()
方法中的參數替換為你想要的紙張尺寸即可。