android - 将android布局转换为PDF文件

标签 android android-layout pdf

如何将 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/

相关文章:

android - react native react 导航安全区域问题

android - 在 HashMap 的 Arraylist 中查找值

Android 在方向更改后从 AsycTask 更新 UI

android - 在屏幕android上更改对话框的位置

javascript - Electron ,来自 BrowserWindow 的 printToPDF

asp.net - Winnovative HTMLtoPDF转换器,添加水印

java - android gridview子项启动 Activity onclick

php - 返回 Cordova 的索引文件

android - Android TV 应用中搜索球旁边的图标

python - PDF 中的标题提取/识别