首页 > 解决方案 > 使用字符串值创建 pdf 文件

问题描述

我正在我的 android 应用程序中生成以下字符串,我想知道是否有一种简单的方法可以从中创建 pdf 或 doc(x) 文件?我已经尝试过 PDFDocument 类,但它对我没有用。抱歉,如果有已知的解决方案,我是 android 和 java 的新手。

String s = "build:              some build name\r\n" + 
                "Version:            25\r\n" + 
                "Specification:      wtx 26.1\r\n" + 
                "\r\n" + 
                "Files to edit:\r\n" + 
                "doc1.doc\r\n" + 
                "doc2.doc\r\n" + 
                "\r\n" + 
                "Notes:\r\n" + 
                "some notes ...";

标签: javaandroidfilepdf

解决方案


在这里您可以轻松创建pdf文件

private void createALlPdf(String str){
    PdfDocument document = new PdfDocument();
    // crate a page description
    PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(600, 1000, 1).create();
    // start a page
    PdfDocument.Page page = document.startPage(pageInfo);
    Canvas canvas = page.getCanvas();
    Paint paint = new Paint();
    //  paint.setColor(Color.RED);
    // canvas.drawCircle(50, 50, 30, paint);
    Date currentTime = Calendar.getInstance().getTime();

    paint.setColor(Color.BLACK);
    // canvas.drawText(wise, 60, 50, paint);
    int y=50;


    canvas.drawText(str, 80, 50, paint);

    canvas = page.getCanvas();
    paint = new Paint();
    // paint.setColor(Color.BLUE);
    // canvas.drawCircle(100, 100, 100, paint);
    document.finishPage(page);
    // write the document content
    String directory_path = Environment.getExternalStorageDirectory().getPath() + "/P-ALLPDF/";
    File file = new File(directory_path);
    if (!file.exists()) {
        file.mkdirs();
    }
    String targetPdf = directory_path+"All record"+currentTime+".pdf";
    File filePath = new File(targetPdf);
    try {
        document.writeTo(new FileOutputStream(filePath));
        Toast.makeText(this, "Pdf file generated in your internal storage under P-ALLPDF directory.Please check!!", Toast.LENGTH_LONG).show();
    } catch (IOException e) {
        Log.e("main", "error "+e.toString());
        Toast.makeText(this, "Something wrong: " + e.toString(),  Toast.LENGTH_LONG).show();
    }
    // close the document
    document.close();
}

通过传递你的字符串来调用函数

createALlPdf(s);

推荐阅读