【问题标题】:How to create and display PDF in Internal Storage/Cache using FileProvider?如何使用 FileProvider 在内部存储/缓存中创建和显示 PDF?
【发布时间】:2018-05-06 18:27:39
【问题描述】:

以下是在外部存储中创建 PDF 的代码。

public class CreatePDF {


private static String FILE = "/xyz";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
        Font.BOLD);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
        Font.NORMAL, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
        Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
        Font.BOLD);
private static Font small = new Font(Font.FontFamily.TIMES_ROMAN, 8,
        Font.ITALIC);

public static final String IMG1 = Environment.getExternalStorageDirectory().getAbsolutePath() + "/xyz/logo.png";





Context context;
String payMode;
String ChecqueNo;
String chequeDate;
String BankName;
String BalAmount,planName;
String Duration;
String StartDate,EndDate,PaidAmount;


String name,recieptNo, receiptDate, memberNo, mobileNo, payamount;



String[] DATA,RecieptData,MemberDATA,plandata;


public CreatePDF(Context context) {
    this.context = context;
}

public void createPDF(String ReceipData,String MemberData,String PayModdata,String PlanData,String bal)
{


    plandata = PlanData.split(",");
    planName=plandata[0];
    Duration=plandata[1];
    StartDate=plandata[2];
    EndDate=plandata[3];
    PaidAmount=plandata[4];


    MemberDATA = MemberData.split(",");
    name=MemberDATA[0];
    memberNo=MemberDATA[1];
    mobileNo=MemberDATA[2];
    payamount=MemberDATA[3];

    DATA = PayModdata.split(",");
    payMode=DATA[0];
    ChecqueNo=DATA[1];
    chequeDate=DATA[2];
    BankName=DATA[3];
    BalAmount=bal;

    RecieptData = ReceipData.split(",");
    recieptNo=RecieptData[0];
    receiptDate=RecieptData[1];



    Document doc = new Document();


    try {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/xyz";

        File dir = new File(path);
        if(!dir.exists())
            dir.mkdirs();

        Log.d("PDFCreator", "PDF Path: " + path);


        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd_ss");
        Date date = new Date();
        File file = new File(dir, name+"_"+recieptNo+".pdf");
        FileOutputStream fOut = new FileOutputStream(file);

        try {
            Document document = new Document();
            PdfWriter.getInstance(document, fOut);
            document.open();
            addMetaData(document);
            addTitlePage(document);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }



    } catch (IOException e) {
        Log.e("PDFCreator", "ioException:" + e);
    }  finally
    {
        doc.close();
    }

}


private static void addMetaData(Document document) {
    document.addTitle("Payment Report");
    document.addSubject("Using iText");
    document.addKeywords("Java, PDF, iText");
    document.addAuthor("author");
    document.addCreator("author");
}


private  void addTitlePage(Document document)
        throws IOException, DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);
    // Lets write a big header






    Paragraph p=new Paragraph("Payment  Receipt", catFont);
    p.setAlignment(Element.ALIGN_CENTER);
    preface.add(p);


    PdfPTable table55 = new PdfPTable(2);
    table55.setWidthPercentage(100);
    table55.setWidths(new int[]{1, 2});
    Image i=Image.getInstance(IMG1);
    i.scalePercent(50f);
    table55.addCell(createImageCell(i));
    table55.addCell(createTextCell("abc \n abc"));
    document.add(table55);
    Paragraph p1=new Paragraph(
            "Report generated At: , " + new Date(),
            smallBold);
    p1.setAlignment(Element.ALIGN_CENTER);
    document.add(new LineSeparator());
    preface.add(p1);
    addEmptyLine(preface, 1);
    document.add(preface);
    document.add(new LineSeparator());
    document.add(Chunk.NEWLINE);
    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.addCell(getCell("Receipt No: "+recieptNo, PdfPCell.ALIGN_LEFT));
    table.addCell(getCell("Receipt Date: "+receiptDate, PdfPCell.ALIGN_CENTER));


    document.add(table);
    document.add(Chunk.NEWLINE);
    PdfPTable table1 = new PdfPTable(1);
    table1.setWidthPercentage(100);
    table1.addCell(getCell("Member No: "+memberNo, PdfPCell.ALIGN_LEFT));
    document.add(table1);
    document.add(Chunk.NEWLINE);


    PdfPTable table11 = new PdfPTable(1);
    table11.setWidthPercentage(100);
    table11.addCell(getCell("Mobile No: "+mobileNo, PdfPCell.ALIGN_LEFT));
    document.add(table11);
    document.add(Chunk.NEWLINE);
    PdfPTable table2 = new PdfPTable(5);
    table2.setWidthPercentage(100);
    table2.addCell(getBoldCell("Pay Mode: ", PdfPCell.ALIGN_LEFT));
    table2.addCell(getBoldCell("Cheque No: ", PdfPCell.ALIGN_CENTER));
    table2.addCell(getBoldCell("Cheque Date: ", PdfPCell.ALIGN_CENTER));
    table2.addCell(getBoldCell("Amount ", PdfPCell.ALIGN_CENTER));
    table2.addCell(getBoldCell("Bank Name:", PdfPCell.ALIGN_CENTER));
    document.add(table2);
    document.add(Chunk.NEWLINE);
    document.add(new LineSeparator());
    PdfPTable table2Copy = new PdfPTable(5);
    table2Copy.setWidthPercentage(100);
    table2Copy.addCell(getCell(payMode, PdfPCell.ALIGN_LEFT));
    table2Copy.addCell(getCell(ChecqueNo, PdfPCell.ALIGN_CENTER));
    table2Copy.addCell(getCell(chequeDate, PdfPCell.ALIGN_CENTER));
    table2Copy.addCell(getCell("Rs. :"+payamount+" INR", PdfPCell.ALIGN_CENTER));
    table2Copy.addCell(getCell(BankName, PdfPCell.ALIGN_CENTER));
    document.add(table2Copy);
    document.add(Chunk.NEWLINE);
    PdfPTable table3 = new PdfPTable(4);
    table3.setWidthPercentage(100);
    table3.addCell(getBoldCell("Plan Name: ", PdfPCell.ALIGN_LEFT));
    table3.addCell(getBoldCell("Duration: ", PdfPCell.ALIGN_CENTER));
    //table3.addCell(getBoldCell("Paid Amount ", PdfPCell.ALIGN_CENTER));
    table3.addCell(getBoldCell("Start Date:", PdfPCell.ALIGN_CENTER));
    table3.addCell(getBoldCell("End Date:", PdfPCell.ALIGN_CENTER));
    document.add(table3);
    document.add(Chunk.NEWLINE);
    document.add(new LineSeparator());
    PdfPTable table3Copy = new PdfPTable(4);
    table3Copy.setWidthPercentage(100);
    table3Copy.addCell(getCell(planName, PdfPCell.ALIGN_LEFT));
    table3Copy.addCell(getCell(Duration, PdfPCell.ALIGN_CENTER));
   // table3Copy.addCell(getCell(PaidAmount, PdfPCell.ALIGN_CENTER));
    table3Copy.addCell(getCell(StartDate, PdfPCell.ALIGN_CENTER));
    table3Copy.addCell(getCell(EndDate, PdfPCell.ALIGN_CENTER));

    document.add(table3Copy);
    document.add(Chunk.NEWLINE);







    Paragraph Para=new Paragraph(
            "Balance Amount : Rs. "+BalAmount+" INR", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold);
    Para.setAlignment(Element.ALIGN_LEFT);
    document.add(Para);
    document.add(Chunk.NEWLINE);
    document.add(new LineSeparator());


    Paragraph ParaTsys=new Paragraph(
            "name", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            small);
    ParaTsys.setAlignment(Element.ALIGN_RIGHT);
    document.add(ParaTsys);

}

public PdfPCell getCell(String text, int alignment) {
    PdfPCell cell = new PdfPCell(new Phrase(text));
    cell.setPadding(0);
    cell.setHorizontalAlignment(alignment);
    cell.setBorder(PdfPCell.NO_BORDER);
    return cell;
}

public PdfPCell getBoldCell(String text, int alignment) {
    Phrase f= new Phrase(text);
    f.setFont(subFont);
    PdfPCell cell = new PdfPCell(f);
    cell.setPadding(0);
    cell.setHorizontalAlignment(alignment);
    cell.setBorder(PdfPCell.NO_BORDER);
    return cell;
}
public static PdfPCell createImageCell(String path,int align) throws DocumentException, IOException {
    Image img = Image.getInstance(path);
    img.scaleAbsolute(100f, 100f);
    img.setAbsolutePosition(500f, 650f);
    PdfPCell cell = new PdfPCell(img, true);
    cell.setHorizontalAlignment(align);
    return cell;
}
private static void addEmptyLine(Paragraph paragraph, int number) {
    for (int i = 0; i < number; i++) {
        paragraph.add(new Paragraph(" "));
    }
}








public static PdfPCell createImageCell(Image img) throws DocumentException, IOException {
    PdfPCell cell = new PdfPCell(img, true);
    cell.setBorder(PdfPCell.NO_BORDER);
    return cell;
}


public static PdfPCell createTextCell(String text) throws DocumentException, IOException {
    PdfPCell cell = new PdfPCell();
    Paragraph p = new Paragraph(text);
    p.setAlignment(Element.ALIGN_RIGHT);
    cell.addElement(p);
    cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
    cell.setBorder(PdfPCell.NO_BORDER);
    return cell;
} }
And Call method like this

 CreatePDF createPDFf= new CreatePDF(PaymentActivity.this);   
createPDFf.createPDF(ReceiptData,MemberData,PayModeData,PlanData,String.valueOf(Bal));

同样请使用 Android 的 InBuilt Feature FILEPROVIDER 提供内部存储解决方案。

以上代码存储在外部存储中。现在几乎每部手机的内部存储器都有足够的空间,所以不需要外部。在这种情况下,我希望在创建和生成 pdf 后存储和检索 pdf。

请提出更改建议。

【问题讨论】:

标签: android file pdf-generation android-fileprovider android-internal-storage


【解决方案1】:

同样请使用 Android 的 InBuilt Feature FILEPROVIDER 提供内部存储解决方案

代替:

   String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/xyz";

    File dir = new File(path);

你会使用:

File dir = new File(context.getFilesDir(), "xyz");

写入内部存储不需要FileProvider。

现在几乎每部手机的内存都有足够的空间,所以不需要外部

使用internal storage 或external storage 的决定不是基于空间的。在大多数 Android 设备上,内部存储和外部存储都位于同一分区上,因此它们占用相同的空间。

相反,问题是:用户是否需要通过文件管理器和类似工具独立访问此 PDF 文件?

如果答案是“是”,请使用外部存储。如果答案是“否”,请使用内部存储。


另外:

  • 请在后台线程上进行磁盘 I/O

  • 请不要将外部存储的根目录与文件混淆

【讨论】:

  • 感谢先生的建议。我目前正在根据给出的答案更新代码。让你知道它是否有效。 FILEPROVIDER 我希望查看创建的 PDF,该 PDF 将根据您的回答存储在内部存储中。 FILEPROVIDER 还将帮助我分享该 pdf,因此您能否建议 FILEPROVIDER 的步骤或查看该 pdf。
  • @Umang: The FileProvider documentation 有使用说明。鉴于我的回答中的代码 sn-p,FileProvider 配置元素将是 &lt;files-path name="whatever" path="xyz" /&gt;(您可以在其中使用您喜欢的任何简单字符串作为 whatever)。
  • 代码已更新,没有错误,但我在哪里可以看到 xyz 目录中的这个文件?请告诉我
  • @Umang:在 Android Studio 中,打开 Device File Explorer 视图。默认情况下,它停靠在右下角。在那里,尝试访问/data/data/.../files/,其中... 是您的applicationId。
  • 先生,我正在运行我的 Android 智能手机。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-15
  • 2017-03-12
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多