I tutorial on how to create a PDF document from a layout or any XML view in Android Studio, I will walk you through the process of using the PdfDocument class to convert your XML views into PDF files. With this powerful functionality, you can generate professional-looking documents within your Android applications. Let’s dive in and explore the steps required to accomplish this. Before we get started, make sure you have the following pre-requisites:
If you are a visual learner, you can find the full video tutorial here:
Create an activity, we have called it main activity, this activity have the XML layout we created above as it’s content view. And we will create two functions.
So once you’ve set the ContentView and added references to the views in the XML above, this is what the activity looks like:
public class MainActivity extends AppCompatActivity Button btnCreatePDF;
Button btnXMLtoPDF;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
askPermissions();
btnCreatePDF = findViewById(R.id.btnCreatePdf);
btnCreatePDF.setOnClickListener(new View.OnClickListener() @Override
public void onClick(View v) createPDF();
>
>);
btnXMLtoPDF = findViewById(R.id.btnXMLToPDF);
btnXMLtoPDF.setOnClickListener(new View.OnClickListener() @Override
public void onClick(View v) convertXmlToPdf();
>
>);
>
>
Note that we have not created the two functions convertXmlToPdf and createPDF as of now. We will implement those methods in the next steps.
In order to save the save the PDF to local storage of android device, we need to ask for runtime permission starting android version 6 and highter. So let’s go ahead and create a function that asks for permission, and add the function in onCreate of our main activity:
private void askPermissions() < ActivityCompat.requestPermissions(this, new String[]WRITE_EXTERNAL_STORAGE>, REQUEST_CODE); >
Also note the variable REQUEST_CODE. In the beginning of MainActivity, above onCreate. Add the following line:
final static int REQUEST_CODE = 1232;
Now let’s get to the good stuff, this is the part where we will implement two functions that will generate PDF. One will write Hello World to the PDF, and another function will convert XML Layout to PDF. Let’s jump into it:
Let’s first look at the whole thing and then we will break it down so that you can understand it better. Here’s what the whole function looks like:
private void createPDF() PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(1080, 1920, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(42);
String text = "Hello, World";
float x = 500;
float y = 900;
canvas.drawText(text, x, y, paint);
document.finishPage(page);
File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String fileName = "example.pdf";
File file = new File(downloadsDir, fileName);
try FileOutputStream fos = new FileOutputStream(file);
document.writeTo(fos);
document.close();
fos.close();
Toast.makeText(this, "Written Successfully. ", Toast.LENGTH_SHORT).show();
> catch (FileNotFoundException e) Log.d("mylog", "Error while writing " + e.toString());
throw new RuntimeException(e);
> catch (IOException e) throw new RuntimeException(e);
>
>
Congratulations! You’ve create your first PDF file from your android app! Now you can create PDF files, and write content to it using canvas. Now let’s see how you can convert an Android View or XML Layout to PDF.
So now that we can draw text to a canvas, and download the PDF to a folder in local storage, let’s see how we can convert XML view or layout to PDF file. As earlier, let’s see the whole code for first:
public void convertXmlToPdf() // Inflate the XML layout file
View view = LayoutInflater.from(this).inflate(R.layout.main_activity, null);
DisplayMetrics displayMetrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) this.getDisplay().getRealMetrics(displayMetrics);
> else
this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.measure(View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, View.MeasureSpec.EXACTLY));
Log.d("mylog", "Width Now " + view.getMeasuredWidth());
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
// Create a new PdfDocument instance
PdfDocument document = new PdfDocument();
// Obtain the width and height of the view
int viewWidth = view.getMeasuredWidth();
int viewHeight = view.getMeasuredHeight();
// Create a PageInfo object specifying the page attributes
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(viewWidth, viewHeight, 1).create();
// Start a new page
PdfDocument.Page page = document.startPage(pageInfo);
// Get the Canvas object to draw on the page
Canvas canvas = page.getCanvas();
// Create a Paint object for styling the view
Paint paint = new Paint();
paint.setColor(Color.WHITE);
// Draw the view on the canvas
view.draw(canvas);
// Finish the page
document.finishPage(page);
// Specify the path and filename of the output PDF file
File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String fileName = "exampleXML.pdf";
File filePath = new File(downloadsDir, fileName);
try // Save the document to a file
FileOutputStream fos = new FileOutputStream(filePath);
document.writeTo(fos);
document.close();
fos.close();
// PDF conversion successful
Toast.makeText(this, "XML to PDF Conversion Successful", Toast.LENGTH_LONG).show();
> catch (IOException e) e.printStackTrace();
// Error occurred while converting to PDF
>
>
The code above demonstrates the process of converting an XML layout file to a PDF document in Android using the PdfDocument class. Now let’s try to understand the code line by line:
In conclusion, this tutorial has demonstrated how to convert an XML layout or any XML view into a PDF document in Android Studio. By utilizing the PdfDocument class and the Canvas API, we were able to create a PDF representation of the XML layout or view.
Remember to handle any necessary permissions and make sure to test your implementation on different devices and screen sizes to ensure compatibility and a smooth user experience.
Let me know in case you run into any issues, Cheers!