java - 使用字符串值创建 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 ...";
解决方案
在这里您可以轻松创建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);
推荐阅读
- javascript - Javascript:在嵌套列表中交换 X 和 Y 值
- angular - 在Angular中执行从一个类到另一个类的函数
- cp - 约束编程中是否有任何传播方法 - GoogleORTools,如 CPLEX-CP 求解器?
- android - 滑动删除列表的元素+子元素
- c# - 无法在 postgresql 中创建表
- c# - 当 7 个布尔值中有 3 个计算为真时如何调用函数
- python - 如何用python在已经存在的文本文件中写入标题
- pymongo - 如何在 Pymongo 中进行批量更新
- javascript - 除了在 Chrome 中看到的 `favicon` 之类的 Electron 中的 `BrowserWindow` 的 `title` 之外,无法设置图标?
- python - 如何从 Python 脚本在后台启动进程并避免僵尸?