How to convert android layout to PDF file. Is it possible?.
If that is possible how to proceed to convert the android layout to PDF.
suggestions are welcome. Thanks in advance.

- 361
- 2
- 4
- 13
-
1ya you can convert layout to bitmap and place it in pdf nothing much.. – jagapathi Jul 19 '17 at 10:30
4 Answers
I have tried many ways.
Finally got an answer Using this library https://mvnrepository.com/artifact/com.itextpdf/itextpdf/5.0.6
Layout to image and place it in 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) {
}
}

- 361
- 2
- 4
- 13
-
1You said *unable to convert view group to image* but actually you did it in your code. – nyconing Nov 08 '18 at 03:27
-
Directly not able to convert layout to image. layout to bitmap and then image. @nyconing – Thirumal Govindaraj Nov 13 '18 at 04:41
-
-
Initially need to create image then add that image on document object ( ***document.add(img);***) – Thirumal Govindaraj Dec 21 '18 at 06:55
-
You can use custom library such as https://github.com/HendrixString/Android-PdfMyXml but there is another way that explained here - How to convert Android View to PDF - that generate a pdf that contains bitmap of your layout

- 181
- 2
- 14
The above answer is correct, it throws an Exception error at the following line.
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Bcoz of this line of code return null
Bitmap bm = relativeLayout.getDrawingCache();
So I have done some more research on Bitmap coming null.I use this method which first converts view to Image. Then you can use above function i.e imageToPDF() which works well.Below is my method.
public void convertCertViewToImage()
{
scrollView.setDrawingCacheEnabled(true);
scrollView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
scrollView.layout(0, 0, scrollView.getMeasuredWidth(), scrollView.getMeasuredHeight());
scrollView.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(scrollView.getDrawingCache());
scrollView.setDrawingCacheEnabled(false); // clear drawing cache
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(getExternalFilesDir(null).getAbsolutePath() + File.separator + "Certificate" + File.separator + "myCertificate.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
}

- 1,421
- 2
- 19
- 43

- 115
- 7
I made a library to achieve this objective.
The main code snippet is -
PdfGenerator.getBuilder()
.setContext(context)
.fromLayoutXMLSource()
.fromLayoutXML(R.layout.layout_print,R.layout.layout_print)
/* "fromLayoutXML()" takes array of layout resources.
* You can also invoke "fromLayoutXMLList()" method here which takes list of layout resources instead of array. */
.setDefaultPageSize(PdfGenerator.PageSize.A4)
/* It takes default page size like A4,A5. You can also set custom page size in pixel
* by calling ".setCustomPageSize(int widthInPX, int heightInPX)" here. */
.setFileName("Test-PDF")
/* It is file name */
.setFolderName("FolderA/FolderB/FolderC")
/* It is folder name. If you set the folder name like this pattern (FolderA/FolderB/FolderC), then
* FolderA creates first.Then FolderB inside FolderB and also FolderC inside the FolderB and finally
* the pdf file named "Test-PDF.pdf" will be store inside the FolderB. */
.openPDFafterGeneration(true)
/* It true then the generated pdf will be shown after generated. */
.build(new PdfGeneratorListener() {
@Override
public void onFailure(FailureResponse failureResponse) {
super.onFailure(failureResponse);
/* If pdf is not generated by an error then you will findout the reason behind it
* from this FailureResponse. */
}
@Override
public void showLog(String log) {
super.showLog(log);
/*It shows logs of events inside the pdf generation process*/
}
@Override
public void onSuccess(SuccessResponse response) {
super.onSuccess(response);
/* If PDF is generated successfully then you will find SuccessResponse
* which holds the PdfDocument,File and path (where generated pdf is stored)*/
}
});

- 6,084
- 3
- 42
- 42
-
I tried this library. But it does not show any results :( the log says it is successfully created. but it is only brought to the file manger and there are no any pdf :( – Isuru Bandara Oct 30 '20 at 06:03
-
-
-
-
Problem solved. and I want to let you know, It does not open the correct folder by default. Thank you for your library it saved my time. – Isuru Bandara Oct 30 '20 at 06:54
-
You are welcomed mostly. Can you please give me an idea about the wrong directory, please? if it is possible can you please share the folder path of yours? – Gk Mohammad Emon Oct 30 '20 at 19:07
-
1It always sends to the download folder, not to the folder we defined. – Isuru Bandara Oct 30 '20 at 19:25
-
@IsuruBandara I fix a lot of folder and file-related issues in my new version. You can try it out. – Gk Mohammad Emon Mar 11 '21 at 20:17