如何使用FileProvider在内部存储/缓存中创建和显示PDF?

时间:2018-05-06 18:27:40

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

以下是在外部存储中创建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。

请建议改变。

1 个答案:

答案 0 :(得分:0)

  

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

而不是:

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

    File dir = new File(path);

你会使用:

File dir = new File(context.getFilesDir(), "xyz");
写入内部存储不需要

FileProvider

  

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

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

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

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

另外:

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

  • 请不要将文件

  • 的外部存储空间弄乱