I have created a PDF file when I clicked the view button in my app. I don't know how to print the same when I click the "Print" button in my app. I have tried by followed some links but it is not working for me.
Link which I have tried - Print existing pdf file in android
The below code, which I was used to create/generate PDF file from my adapter file.
SampleAdapter.java
------------------------
private void createPdf(String id) throws FileNotFoundException, DocumentException {
File pdfFolder = new File(Environment.getExternalStorageDirectory(), "pdfdemo");
//File pdfFolder = new File(context.getFilesDir(), "pdfdemo");
if (!pdfFolder.exists()) {
pdfFolder.mkdirs();
Log.e("LOG_TAG", "Pdf Directory created"+pdfFolder);
}
//Create time stamp
Date date = new Date() ;
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
File myFile = new File(pdfFolder +"/"+ timeStamp + ".pdf");
OutputStream output = new FileOutputStream(myFile);
//Step 1
Document document = new Document(PageSize.A4, 36, 36, 36, 36);
//Step 2
PdfWriter writer = PdfWriter.getInstance(document, output);
//Step 3
document.open();
// add image
Drawable d = context.getResources().getDrawable(R.drawable.na);
BitmapDrawable bitDw = ((BitmapDrawable) d);
Bitmap bmp = bitDw.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = null;
try {
image = Image.getInstance(stream.toByteArray());
image.scaleToFit(100,100);
// image.setAbsolutePosition( 0,180);
image.setAlignment(Element.ALIGN_LEFT);
} catch (IOException e) {
e.printStackTrace();
}
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);
table.setWidths(new int[]{1, 3});
table.addCell(image);
PdfPCell cell = new PdfPCell();
Font green = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD, BaseColor.GREEN);
Chunk redText = new Chunk("NATIONAL AGRO FOUNDATION", green);
Paragraph p = new Paragraph();
p.setAlignment(Element.ALIGN_CENTER);
p.add(redText);
cell.addElement(p);
Font black = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK);
Chunk text2 = new Chunk("LABORATARY SERVICES DIVISION", black);
Paragraph p2 = new Paragraph();
p2.setAlignment(Element.ALIGN_CENTER);
p2.add(text2);
cell.addElement(p2);
Font black2 = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLACK);
Chunk text3 = new Chunk("Tharamani, Chennai, Tamil Nadu 600113", black2);
Paragraph p3 = new Paragraph();
p3.setAlignment(Element.ALIGN_CENTER);
p3.add(text3);
cell.addElement(p3);
Font black3 = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLACK);
Chunk text4 = new Chunk("Phone: 044 2254 2803", black3);
Paragraph p4 = new Paragraph();
p4.setAlignment(Element.ALIGN_CENTER);
p4.add(text4);
cell.addElement(p4);