Skip to content

mddanishansari/html-to-pdf-convertor

Repository files navigation

HTML to PDF Convertor

A simple HTML to PDF convertor for Android

Download

Add mavenCentral() repository in project's build.gradle

allprojects {
    repositories {
        // Possibly other repositories
        mavenCentral()
    }
}

Add dependency in module's build.gradle

dependencies {
    // Possibly other dependencies
    // Replace the <latest-version> with actual latest version
    implementation 'io.github.mddanishansari:html-to-pdf-convertor:<latest-version>'
}

Usage

Create an instance of HtmlToPdfConvertor class

val htmlToPdfConvertor = HtmlToPdfConvertor(context)

Set optional base URL

htmlToPdfConvertor.setBaseUrl("file:///android_asset/images/") // is null by default

To generate dynamic content using JS

htmlToPdfConvertor.setJavaScriptEnabled(true)

Start the conversion by calling convert function

htmlToPdfConvertor.convert(
  pdfLocation = pdfLocation, // the file location where pdf should be saved
  htmlString = htmlString, // the HTML string to be converted
  onPdfGenerationFailed = { exception -> // something went wrong, handle the exception (this param is optional) 
      exception.printStackTrace()
  },
  onPdfGenerated = { pdfFile -> // pdf was generated, do whatever you want with it
      openPdf(pdfFile)
  })

Storage permission is required to save pdf file on storage

Checkout sample code, also sample HTML and PDF