我正在创建一个printdocumentadapter类来生成要打印的pdf。我需要根据我的数据变量(只是一个包含文本的字符串)自动计算需要多少页。因此,在实际使用onwrite方法实例化画布对象之前,我需要先以像素或dp找出画布的宽度和高度。这是课程文件:
public class CustomPrintDocumentAdapter extends PrintDocumentAdapter {
private Activity cur;
private int pageCount = 1;
private PrintedPdfDocument pdf;
private String data;
private int textSize = 16;
public CustomPrintDocumentAdapter(Activity current, String data){
this.cur = current;
this.data = data;
}
@Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {
pdf = new PrintedPdfDocument(cur,newAttributes);
if(cancellationSignal.isCanceled()){
callback.onLayoutCancelled();
}
PrintDocumentInfo info = new PrintDocumentInfo.Builder("print_output.pdf").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).setPageCount(pageCount).build();
callback.onLayoutFinished(info,true);
}
@Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
PdfDocument.Page page = pdf.startPage(1);
drawPage(page);
pdf.finishPage(page);
try{
pdf.writeTo(new FileOutputStream(destination.getFileDescriptor()));
}catch(IOException ie){
callback.onWriteFailed(ie.toString());
}finally{
pdf.close();
}
callback.onWriteFinished(pages);
}
public void drawPage(PdfDocument.Page page){
Canvas canvas = page.getCanvas();
TextPaint paint = new TextPaint();
paint.setColor(Color.BLACK);
paint.setTextSize(16);
StaticLayout.Builder.obtain(data,0,data.length(),paint,canvas.getWidth()).build().draw(canvas);
Log.d("CustomPrintDocumentAdapter","Canvas width in pixels: "+canvas.getWidth());
//prints D/CustomPrintDocumentAdapter: Canvas width in pixels: 590
//Canvas width in pixel is 590px????
//my screen is only 480 pixels wide yet the canvas displayed is smaller than my screen??
}
}
所以我的问题是如何在onLayout方法中以像素为单位找到画布对象的宽度和高度?
我正计划使画布填充纸上的所有区域(任何尺寸)。