Generating PDFs with multiple pages using android.graphics.pdf

Currently, I am facing an issue while attempting to generate a PDF using android.graphics.pdf. The problem arises when dealing with multiple pages in the document. While I can provide android.graphics.pdf with HTML content that could be converted into a PDF format, it fails when text exceeds the predetermined page size. My question is, is there a way to input all the HTML content and have it automatically split into multiple pages based on the content's size in relation to the page dimensions? This functionality is similar to what TCPDF offers :)

It's worth mentioning that I want to avoid manually creating separate pages by calculating content height.

Answer №1

To incorporate the iTextG jar file into your project, follow these steps:

   public void generateAndShowPdf(String text) {

    Document doc = new Document();

    try {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir";

        File dir = new File(path);
        if(!dir.exists())
            dir.mkdirs();

        File file = new File(dir, "newFile.pdf");
        FileOutputStream fOut = new FileOutputStream(file);

        PdfWriter.getInstance(doc, fOut);

        //open the document
        doc.open();

        Paragraph p1 = new Paragraph(text);
        Font paraFont= new Font(Font.COURIER);
        p1.setAlignment(Paragraph.ALIGN_CENTER);
        p1.setFont(paraFont);

        //add paragraph to document
        doc.add(p1);    

    } catch (DocumentException de) {
        Log.e("PDFCreator", "DocumentException:" + de);
    } catch (IOException e) {
        Log.e("PDFCreator", "ioException:" + e);
    }
    finally {
        doc.close();
    }

    displayPdf("newFile.pdf", "Dir");
}

// Method for displaying a pdf file
private void displayPdf(String file, String directory) {

    File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
    Uri path = Uri.fromFile(pdfFile);

    // Setting the intent for pdf reader
    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
    pdfIntent.setDataAndType(path, "application/pdf");
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    try {
        startActivity(pdfIntent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(TableActivity.this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting Data from MySQL and PHP to Excel

Is there a way to export human resource applications stored in my MySQL table as an Excel file? function exportExcel($filename='ExportExcel',$columns=array(),$data=array(),$replaceDotCol=array()){ global $connect; header('Content-Enc ...

Several validation checks - logic malfunction

I have implemented a validation feature for passwords on a form, but I suspect there may be a logic error in my code that I haven't caught yet (blame it on the coffee machine!). Take a look at the JavaScript below: <script type="text/javascript"& ...

Arrow smoothly sliding beneath the selected tab in the active menu

Here is a reference picture. https://i.sstatic.net/wsp6R.png I am trying to create a slide effect for my arrow when clicking on different menu items. The arrow should move over the active menu item. By default, the arrow should point to the active menu. ...

Transform an HTML website into a collaborative wiki platform

I currently have a simple HTML website (no JavaScript, PHP, or CSS) with over 1000 pages that I want to transform into a Wiki format. I need a converter to extract the content from each page and create individual wiki pages for them. Additionally, all the ...

Instructions for converting a readonly text field into an editable one using JavaScript

I'm trying to make it so that when the button (with id name_button) is clicked, the text field (with id name_text_field) becomes enabled. However, my current code doesn't seem to be working. Here's a snippet of my HTML: <input type="tex ...

Customizing the file path for the PDF worker: A step-by-step guide

Incorporating the PDF Viewer Component from this source into an Angular 7 project has been a challenge. The documentation clearly states: The default worker is loaded from cdnjs.cloudflare.com. My goal is to load the worker from a local path within my ...

SVGs do not display on iPhones

Having some issues with my code - specifically, I have an SVG animation that seems to work on all devices except iPhones. I've been struggling to find a solution. Here is the code snippet for the SVG: <div class="contenuto-svg"> <svg vi ...

Creating an anchor element with text and a bootstrap icon involves using the appropriate HTML structure and

I am trying to figure out how to create an element that includes both text and a Bootstrap icon. Here is the HTML code: <a> Edit <i class="icon-pencil" /> </a> Can anyone help me understand how to select this DOM element using jQuer ...

Using CSS to enforce a specific height for text by overflowing its parent container horizontally

I have a lengthy phrase that takes up too much space on mobile devices. Here is an example: .artificial-phone-viewport { width: 320px; height: 500px; border: 1px solid darkgrey; } .container { width: 100%; height: 100%; } .text { /* * Do ...

How to make a multiline TextInput automatically scroll to the bottom in a react native app

I am trying to create a TextInput component where the text is visible when the keyboard is on. Android usually does this by default, but for some reason, my multiline TextInput is scrolling down to the bottom of the text just like a single line input (with ...

Using either Google Maps or a customized mapping solution in a React Native application

I am currently developing an application that allows users to input addresses and locate them on a map. I am wondering if implementing AI technology or utilizing specific libraries is necessary in order for this feature to function properly within a reac ...

Using an image instead of a checkbox when it is selected (Angular 4/Ionic 3)

Is there a way to swap out the checkbox for an image? I want this image to change dynamically based on whether the checkbox is checked or not. Unfortunately, adding a class doesn't seem to do the trick as it modifies all icons in the same column. The ...

Issues with Opera displaying specific characters when using webfonts

Perhaps it's not supposed to work this way, but hear me out. I'm utilizing Google Web Fonts and adding the PT Sans font like this: <link href="https://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic" rel="stylesheet" ty ...

I'm looking for a JQuery plugin that can lock an element in place as you scroll through a webpage

My query is not regarding position:fixed. While scrolling down the page, I aim for the element to move down along with the page until it goes beyond the view of the browser. Once it goes out of the view, it should stay close to the top of the page, yet st ...

The functionality of HTTP requests using OkHttp Interceptor is not functioning properly

I am utilizing Retrofit in combination with OkHttp Interceptor for API interaction. The Interceptor is responsible for adding a cookie header to each request. Here is the code for the Interceptor: class AddCookiesInterceptor: Interceptor { @Inject ...

Exploring ways to retrieve complete HTML content from a Single Page Application using AJAX?

Seeking assistance in obtaining the complete HTML generated by a Single Page Application built on AngularJS. $.get('http://localhost:3388/' + d.response.path, function (d) { $('#templateContainer').html(d); ...

How to Position Buttons at the Bottom of a Card with Bootstrap

When creating a card for certain items, I am using the code below. To align the button at the bottom of the card, I have implemented the following: return ' <div class="col"> <div class="card detail ...

Failed to change working directory (error code 2: File or directory not found)

When I try to run my project in Android Studio, I keep getting this error: Any idea what could be causing it? 10:04:15 PM: Executing task 'installDebug'... Could not set process working directory to '/Users/mahdir/.gradle/daemon/4.8/:app& ...

Where can I locate the definition of a div in WordPress?

Recently, I installed a new template on my WordPress blog. However, the template designer added a footer copyright that I am unable to delete. It seems like the copyright text is not located in any of the PHP or CSS files. Upon inspecting the elements, I f ...

What are the best methods for creating a responsive webpage with images and text in the header?

My webpage features a razor page with a header component called PageHeader.razor. I have been attempting to make it responsive, but I am facing an issue where the text and image overlap when viewed in responsive mode. What could be causing this problem? ...