如何将 android 布局转换为 PDF 文件。可能吗?。
如果可能的话,如何继续将 android 布局转换为 PDF。
欢迎提出建议。提前致谢。
最佳答案
我试过很多方法。
终于得到答案 使用这个库https://mvnrepository.com/artifact/com.itextpdf/itextpdf/5.0.6
布局到图像并将其放入pdf
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
String dirpath;
public void layoutToImage(View view) {
// get view group using reference
relativeLayout = (RelativeLayout) view.findViewById(R.id.print);
// convert view group to bitmap
relativeLayout.setDrawingCacheEnabled(true);
relativeLayout.buildDrawingCache();
Bitmap bm = relativeLayout.getDrawingCache();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
}
public void imageToPDF() throws FileNotFoundException {
try {
Document document = new Document();
dirpath = android.os.Environment.getExternalStorageDirectory().toString();
PdfWriter.getInstance(document, new FileOutputStream(dirpath + "/NewPDF.pdf")); // Change pdf's name.
document.open();
Image img = Image.getInstance(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - 0) / img.getWidth()) * 100;
img.scalePercent(scaler);
img.setAlignment(Image.ALIGN_CENTER | Image.ALIGN_TOP);
document.add(img);
document.close();
Toast.makeText(this, "PDF Generated successfully!..", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
关于android - 将android布局转换为PDF文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45187875/