我正在开发一个项目,用于从android中的编辑文本字段创建Pdf文件。我已经从互联网上研究了很多关于如何做到这一点,主要找到两个库iText和Apwlibrary来做这个,但是我找不到任何可靠的代码来做到这一点没有错误,也没有任何涵盖所有领域的教程这需要注意这个工作。不知怎的,我把所有东西和我非常有限的android知识结合起来制作一个基本的pdf文件,但现在我卡住了,我不知道如何在pdf文件中添加更多数据。这是我最终提出的代码。
private void createPdf() throws FileNotFoundException{
File pdfFolder=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS),"pdfdemo");
if(!pdfFolder.exists()){
pdfFolder.mkdir();
Log.d("SelfNoteFragment"," Pdf Created");
}
Date date = new Date();
String timeStamp=new SimpleDateFormat("yyyMMdd_HHmmss").format(date);
File myFile= new File(pdfFolder+timeStamp+".pdf");
OutputStream outputStream=new FileOutputStream(myFile);
PdfDocument pdfDocument= new PdfDocument();
DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height=displayMetrics.heightPixels,
width=displayMetrics.widthPixels;
PdfDocument.PageInfo pageInfo= new PdfDocument.PageInfo.Builder(width,height,4).create();
PdfDocument.Page page=pdfDocument.startPage(pageInfo);
mRootView.draw(page.getCanvas());
pdfDocument.finishPage(page);
try{
pdfDocument.writeTo(outputStream);
}catch (IOException e){
}
}
我是菜鸟,所以如果问题不包含相关点或问题含糊不清,请在下面的评论中指定。我已经通过关于代码的android文档,但由于我的知识有限,我无法想象我想做什么。我想尽可能具体,但如果问题仍然含糊不清,请说明所需的要点,我会更具体。谢谢。
答案 0 :(得分:1)
创建一个新类CreatePDF。
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;
} }
和这样的呼叫方法
CreatePDF createPDFf= new CreatePDF(PaymentActivity.this);
createPDFf.createPDF(ReceiptData,MemberData,PayModeData,PlanData,String.valueOf(Bal));
请忽略代码中的拼写错误。
输出看起来像这样。
答案 1 :(得分:0)
private void LatterPadPdf() {
final Calendar c = Calendar.getInstance();
int yyyy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH);
String months;
if (mm > 8) {
mm = mm + 1;
months = String.valueOf(mm);
} else {
mm = mm + 1;
months = "0" + String.valueOf(mm);
}
int dd = c.get(Calendar.DAY_OF_MONTH);
fileNameFormat = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
filename = "QUOT_" + (PreferenceManager.getDefaultSharedPreferences(this).getString("LOGIN_USERNAME", null)) + "_" +
PreferenceManager.getDefaultSharedPreferences(this).getString("Customer_short_code", "") + "_" + fileNameFormat;
filename = filename + ".pdf";
latterpadfilename = filename;
String currentDate = new StringBuilder().append(dd).append("/").append(months).append("/").append(yyyy).toString();
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.v(LOG_TAG, "External Storage not available or you don't have permission to write");
} else {
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("pdf_path", null));
if (myFile.exists()) {
pdfFile_latter = new File(myFile, filename);
} else {
myFile = new File("/sdcard" + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("pdf_path", null));
myFile.mkdirs();
pdfFile_latter = new File(myFile, filename);
}
// pdfFile = new File(getExternalFilesDir(filepath), filename);
}
Document document = new Document();
try {
PdfWriter docWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile_latter));
docWriter.setPageEvent(new PDFBackground());
document.open();
addEmptyLine(document, 3);
document.add(tableGoldUsername("Date : " + currentDate));
addEmptyLine(document, 1);
document.add(tablemethod_MR("To, ", "MR : " + rSharedpreference.getString("EmpName", "")));
//-----------------------------------------------
document.add(tableGoldUsername(CheckValues(rSharedpreference.getString("name_new", ""))));
document.add(tablemethod_new(CheckValues(rSharedpreference.getString("address_new", ""))));
document.add(tablemethod_new(CheckValues(rSharedpreference.getString("city_new", ""))));
document.add(tablemethod_new(CheckValues(rSharedpreference.getString("state_new", ""))));
document.add(tablemethod_new(CheckValues(rSharedpreference.getString("pin_new", ""))));
document.add(tablemethod_new(CheckValues(rSharedpreference.getString("mobile_new", ""))));
document.add(tablemethod_new(CheckValues(rSharedpreference.getString("email_new", ""))));
addEmptyLine(document, 1);
document.add(tableHeader(" QUOTATION "));
addEmptyLine(document, 1);
// document.add(tableDaimondRate());
document.add(tableGoldParagraph("Shall be as per the market price at the time of delivery."));
document.add(tableGoldParagraph("Labour Charges :- ", "All items shall be @ " + rSharedpreference.getString("gram_rate", "") +
" xxxxxxxx @ " + rSharedpreference.getString("min_rate", "")));
addEmptyLine(document, 1);
document.add(tableHeader(" TERMS AND CONDITIONS "));
addEmptyLine(document, 1);
document.add(tableGoldParagraph("Delivery :- ", "Within 35 to 40 working days from the date of final approved order."));
document.add(tableGoldParagraph("Payment :-", "xxxxxx"));
document.add(tableGoldParagraph("Damaged :-", "xxxxxx"));
// document.add(tableGoldParagraph("Return Policy :-", "We have no return policy applicable in the generic products or multiple orders placed in the same category"));
document.add(tableGoldParagraph("Supporting Documents :-", "xxxxxxx."));
document.add(tableGoldParagraph("Size :-", "xxxxxx"));
addEmptyLine(document, 1);
document.add(tableGoldParaNote("", " xxxxx"));
addEmptyLine(document, 1);
document.add(tableGoldParaNote("Note :-", "xxxxx "));
document.add(tableGoldParagraph("DISCLAIMER :-", "xxxxxx"));
document.add(tableGoldParagraph("", "xxxx"));
document.add(tableGoldParagraph("", "xxxx"));
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
首选参考文献。 http://developers.itextpdf.com/examples/itext-action-second-edition/chapter-1