我无法使用 Android

问题描述

开发人员!我正在使用 PdfDocument 尝试将文本保存为 pdf 文件。所以我写了这段代码:

 public void Convert(String text,String fileName){
    PdfDocument myPdfDocument = new PdfDocument();
    PdfDocument.PageInfo myPageInfo = new PdfDocument.PageInfo.Builder(this.pageWidth,this.pageHeight,this.pageNumber).create();
    PdfDocument.Page myPage = myPdfDocument.startPage(myPageInfo);

    Paint myPaint = new Paint();
    Paint backPaint = new Paint();
    backPaint.setColor(this.backgroundcolor);
    myPaint.setTextSize(this.textSize);
    myPaint.setColor(this.fontcolor);

    //To find size of screen so that line is perfectly fit
    DisplayMetrics dm = this.context.getResources().getDisplayMetrics();
    int widthOfScreen = dm.widthPixels;
    int periodForSplittingText = widthOfScreen / Math.round(this.textSize);

    // To make line split in width of the screen here;
    String insert = "\n";
    
    StringBuilder builder = new StringBuilder(
     text.length() + insert.length() * (text.length()/periodForSplittingText)+1);

    int index = 0;
    String prefix = "";
    while (index < text.length()){
        builder.append(prefix);
        prefix = insert;
        builder.append(text.substring(index,Math.min(index + periodForSplittingText,text.length())));
        index += periodForSplittingText;
       
    }
    
    


    String myString = builder.toString();

    for (String line:myString.split("\n")){
        myPage.getCanvas().drawPaint(backPaint);
        myPage.getCanvas().drawText(line,this.x,this.y,myPaint);
        y+=myPaint.descent()-myPaint.ascent();
        
    }
    myPdfDocument.finishPage(myPage);

// Started another page 
myPdfDocument.startPage(myPageInfo);
myPage.getCanvas().drawText("Second Page Text",14,25,myPaint);
myPdfDocument.finishPage(myPage);



    String myFilePath = Environment.getExternalStorageDirectory().getPath() + this.filePath + "/" + fileName;
    File myFile = new File (myFilePath);
    try {
        myPdfDocument.writeTo(new FileOutputStream(myFile));

    } catch (Exception e) {
        e.printStackTrace();
    }
    
    myPdfDocument.close();
}

但是如果我输入了长文本,则无法在两页上创建它。根据 Android 开发者的

这个类可以从原生 Android 内容生成 PDF 文档。您创建一个新文档,然后为要添加的每个页面开始一个页面,将内容写入该页面,然后完成该页面。完成所有页面后,将文档写入输出流并关闭文档。文档关闭后,您不应再使用它。请注意,页面是一个接一个地创建的,即您在任何给定时间只能有一个页面用于写入。这个类不是线程安全的。

但我不明白这是什么意思? 我该如何解决这个问题?帮助

编辑: 现在添加这个

// Started another page 
myPdfDocument.startPage(myPageInfo);
myPage.getCanvas().drawText("Second Page Text",myPaint);
myPdfDocument.finishPage(myPage);

导致此错误:尝试在空对象引用上调用虚拟方法“void android.graphics.Canvas.drawText(java.lang.String,float,android.graphics.Paint)”

解决方法

当你开始一个新页面时,你并没有将它分配给一个变量

改为

// Started another page 
myPage = myPdfDocument.startPage(myPageInfo);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...