@TargetApi(Build.VERSION_CODES.KITKAT) class MyPrintDocumentAdapter(private var context:Context):PrintDocumentAdapter(){ private var pageHeight:Int = 0 private var pageWidth:Int = 0 var myPdfDocument:PdfDocument? =空 var totalpages = 4 私人var bm:SpannableStringBuilder? =空 重写fun onLayout(oldAttributes:PrintAttributes,newAttributes:PrintAttributes,cancellationSignal: CancellationSignal,回调:LayoutResultCallback,元数据:捆绑){ myPdfDocument = PrintedPdfDocument(上下文,newAttributes) pageHeight = newAttributes.mediaSize !!。heightMils / 500 * 72 pageWidth = newAttributes.mediaSize !!。widthMils / 500 * 72 如果(cancellationSignal.isCanceled){ callback.onLayoutCancelled() 返回 } 如果(总页数> 0){ val builder = PrintDocumentInfo.Builder(“ $ heading.pdf”) .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT) .setPageCount(总页数) val info = builder.build() callback.onLayoutFinished(info,true) }其他{ callback.onLayoutFailed(“页面数为零。”) } } 重写fun onWrite(pageRanges:数组,目标:ParcelFileDescriptor,cancellationSignal: CancellationSignal,回调:WriteResultCallback){ 的(i在0到总页数中){ 如果(pageInRange(pageRanges,i)){ val newPage = PdfDocument .PageInfo.Builder( pageWidth, pageHeight,我 )。创建() val page = myPdfDocument !!。startPage(newPage) 如果(cancellationSignal.isCanceled){ callback.onWriteCancelled() myPdfDocument !!。close() myPdfDocument = null 返回 } drawPage(page,i) myPdfDocument !!。finishPage(页面) } } 尝试{ myPdfDocument !!。writeTo( FileOutputStream( destination.fileDescriptor ) ) } catch(e:IOException){ callback.onWriteFailed(e.toString()) 返回 }最后{ myPdfDocument !!。close() myPdfDocument = null System.err.println(“完成!”) } callback.onWriteFinished(pageRanges) } private fun pageInRange(pageRanges:Array,page:Int):布尔值{ 为(i在pageRanges.indices中){ if(page> = pageRanges [i] .start && page <= pageRanges [i] .end) 返回真 } 返回假 } 私人趣味drawPage( 页面:PdfDocument.Page, pagnumber:整数 ){ var pagnumber = pagnumber val canvas = page.canvas pagnumber ++ //确保页码从1开始 // val titleBaseLine = 72 // val leftMargin = 38 val paint = Paint() paint.color = Color.BLACK paint.textSize = 40f val pageInfo = page.info val徽标= BitmapFactory.decodeResource(context.resources,R.drawable.karma) canvas.drawBitmap(徽标,(pageInfo.pageWidth / 2-logo.width / 2).toFloat(),0f,绘画) bm =组合 val mTextPaint = TextPaint() val mTextLayout = StaticLayout(combination,mTextPaint,canvas.getWidth(),Layout.Alignment.ALIGN_CENTER, 1.0f,0.0f,true); mTextLayout.draw(画布) paint.textSize = 18f canvas.drawText(“ Page No. $ pagnumber”,(pageInfo.pageWidth / 2-“ Page No. $ pagnumber” .length).toFloat(), (pageInfo.pageHeight-10).toFloat(),绘制)}} val btnPrint = findViewById(R.id.printButton) btnPrint.setOnClickListener { val printManager =此 .getSystemService(Context.PRINT_SERVICE)作为PrintManager val jobName = this.getString(R.string.app_name)+“ $ heading” println(“ jobName:$ jobName”) printManager.print(jobName,MyPrintDocumentAdapter(this),null) }
第二页无法打印。不知道我在哪里做错。请引导我