Showing posts with label pdf. Show all posts
Showing posts with label pdf. Show all posts

Thursday, February 9, 2023

html2pdf.js | Client-side HTML-to-PDF rendering using pure JS JavaScript

Import html2pdf using CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"/>
Once installed, html2pdf.js is ready to use. The following command will generate a PDF of #element-to-print and prompt the user to save the result:
var element = document.getElementById('element-to-print');
html2pdf(element);
Below is a advance example using header and footer:
var date = new Date().toISOString().split("T")[0];
var opt = {
    margin:       0.5,
    filename:     'work-log-report-' + date + '.pdf',
    enableLinks:  false,
    pagebreak:    { mode: 'avoid-all' },
    image:        { type: 'jpeg', quality: 0.98 },
    html2canvas:  { scale: 2 },
    jsPDF:        { unit: 'in', format: 'a4', orientation: 'portrait' }
};
var element = document.getElementById('element-to-print');
html2pdf().from(element).set(opt).toPdf().get('pdf').then(function (pdf) {
    console.log("Done");

    var totalPages = pdf.internal.getNumberOfPages();
    for (var i = 1; i <= totalPages; i++) {
        pdf.setPage(i);
        pdf.setFontSize(10);
        pdf.setTextColor(150);
        pdf.text('Work Log Report - ' + date, (pdf.internal.pageSize.getWidth()/2) - 0.99, 0.35);
        pdf.text('Page ' + i + ' of ' + totalPages, (pdf.internal.pageSize.getWidth()/2) - 0.3, pdf.internal.pageSize.getHeight() - 0.25);
    }
}).save();
Output would be as below:

Live Example

html2pdf.js converts any webpage or element into a printable PDF entirely client-side using html2canvas and jsPDF.
Company Name Employee Name Country
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name
Some company name which is very bigemployee-name-without-any-space-between-those-wordsCountry-name

Saturday, May 25, 2019

jQuery convert PDF to Images Page by Page using pdfjsLib from Mozilla Foundation

First download pdf.js and pdf.workder.js from here or use direct link //mozilla.github.io/pdf.js/build/pdf.js and //mozilla.github.io/pdf.js/build/pdf.worker.js.

<script src="pdf.js"></script>

<title>PDF.js 'Hello, world!' example</title>

<h1>PDF.js 'Hello, world!' example</h1>

<canvas id="the-canvas" style="border:1px solid red;"></canvas>

<script type="text/javascript">
  var url = './sample2.pdf';

  // Loaded via <script> tag, create shortcut to access PDF.js exports.
  var pdfjsLib = window['pdfjs-dist/build/pdf'];

  // The workerSrc property shall be specified.
  pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';

  // Asynchronous download of PDF
  var loadingTask = pdfjsLib.getDocument(url);
  loadingTask.promise.then(function(pdf) {
    console.log('PDF loaded, total pages = ' + pdf.numPages);

    // Fetch the first page
    var pageNumber = 1;
    pdf.getPage(pageNumber).then(function(page) {
      console.log('Page loaded');

      var scale = 1.5;
      var viewport = page.getViewport({scale: scale});

      // Prepare canvas using PDF page dimensions
      var canvas = document.getElementById('the-canvas');
      var context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      // Render PDF page into canvas context
      var renderContext = {
        canvasContext: context,
        viewport: viewport
      };
      var renderTask = page.render(renderContext);
      renderTask.promise.then(function () {
        console.log('Page rendered');
      });
    });
  }, function (reason) {
    // PDF loading error
    console.error(reason);
  });
</script>

Friday, May 12, 2017

HTML2PDF Ahead of TCPDF - PHP PDF LIBRARY

Generate PDF from Html is always difficult, because if you want a better look PDF then you must need to spend good amount of time of it. TCPDF is well known to us as a rich PDF library. No problem with it but HTML2PDF is some type of as layer over TCPDF which makes it better. It has great custom page header and footer support.

Below is a code snippet:

require_once(dirname(__FILE__) . '/../vendor/autoload.php');
try {
    $html2pdf = new HTML2PDF('P', 'A4', 'en');
    $html2pdf->setDefaultFont('Arial');
    $html2pdf->writeHTML($html_content);
    $html2pdf->Output('PdfName.pdf');
} catch (HTML2PDF_exception $e) {
    echo $e;
    exit;

}

You can download full example code from link below.
Click here to download.

Below are attached some screenshots:






Friday, April 14, 2017

Laravel 5.x Install DOM-PDF

Laravel is a strong php based framework today. Its very important that we can create PDF using our application. Laravel & DOM-PDF both makes it easy. Just follow the following steps:

1. Add the following line to "composer.json" in "require" section:

"barryvdh/laravel-dompdf": "^0.8.0"

2. Open command prompt and navigate to project directory & execute following command:

composer update barryvdh/laravel-dompdf --lock

Above command will install dompdf in your project

3. After installation open "conig/app.php" and add following line to providers:

Barryvdh\DomPDF\ServiceProvider::class

4. Add the following line to create an alias for dompdf:

'PDF' => Barryvdh\DomPDF\Facade::class

5. Now create a folder named "fonts" in "storage" folder.

This folder will used to store font cache.

6. Now create a Controller as follows:



<?php
namespace App\Http\Controllers;

use PDF;
use Illuminate\Routing\Controller as BaseController;

class HomeController extends BaseController
{
    public function pdf()
    {
        $pdf = PDF::loadView('home.pdf');
        //return $pdf->download('review.pdf'); //Download        
        return $pdf->stream('review.pdf'); //Stream    
    }
}
?>


7. Now create a view under "resource/views/home" named "pdf.blade.php" with following contents:


<!DOCTYPE html>
<html lang="en" >
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
</head>
<body>
<h1>Test PDF</h1>
</body>
</html>


8. Add the following line to "routes/web.php":


Route::get('/pdf', "HomeController@pdf");

9. Now browser {{Base_Url}}/pdf to view your pdf:




10. You are done.

Tuesday, February 21, 2017

Create Thubmnail / Image From Each Page of a PDF Using Java

It is very important to make some thumbnails from pdf in our application. Using java it is now very easy to do this task. You have to open your pdf using java program then you can set which page (0...n) you want to make to thumbnail. Then you can save that as image to your server or desktop machine.

To complete this task you need to download PDFRenderer-0.9.1.jar.

You can download whole package from here.

Sample java code:

package com.pkm;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by pritom on 26/12/2016.
 */
public class ThumbnailFromPdf {
    public static void main(String[] args) throws Exception {
        File file = new File("src/com/pkm/PDF.pdf");
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        FileChannel fileChannel = randomAccessFile.getChannel();
        ByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
        PDFFile pdfFile = new PDFFile(byteBuffer);
        PDFPage pdfPage = pdfFile.getPage(0);
        Rectangle rectangle = new Rectangle(0, 0, (int) pdfPage.getBBox().getWidth(), (int) pdfPage.getBBox().getHeight());
        Image image = pdfPage.getImage(rectangle.width, rectangle.height, rectangle, null, true, true);
        ImageIO.write((RenderedImage) image, "png", new File("src/com/pkm/PDF.png"));
    }
}

Sample output would be like something depends on your pdf file:


 

Monday, August 1, 2016

Salesforce PDF Viewer with custom PDF page

1. First create a apex class with following contents:

global with sharing class QuoteCustomPdfGenerator {
    private ApexPages.StandardController sc;
    public Quote q {get; private set;}
    public String id {get; private set;}

    public QuoteCustomPdfGenerator(ApexPages.StandardController controller) {
        this.sc = sc;
        this.id = ApexPages.currentPage().getParameters().get('Id');
        this.q = [SELECT Id,Name From Quote WHERE Id=:this.id];
    }
    
    public PageReference viewPdf() {
        return null;
    }

    webService static String createQuotePdf(String Id) {
        try {
            PageReference pageRef = new PageReference('/apex/QuoteCustomPdfView?Id='+Id);
            Blob content = pageRef.getContent();
            QuoteDocument doc = new QuoteDocument(Document = content, QuoteId = Id);
            insert doc;

            return 'SUCCESS';
        } 
        catch(exception ex) {
           System.debug('--- Error ----------'+ ex);
           return ex.getMessage();
        }
    }
}

2. Now create a visualforce page with following contents (Name of visualforce page="QuoteCustomPdfView"):

<apex:page standardController="Quote" extensions="QuoteCustomPdfGenerator" action="{!viewPdf}" renderAs="pdf">
    This is my custom pdf for the quote=[[{!q.Name}]]
</apex:page>

3. Create a local js file with following contents:

function SaveQuoteAsCustomPDF(quoteId) {
    try {
        var res = sforce.apex.execute("QuoteCustomPdfGenerator","createQuotePdf",{Id : quoteId});
        if(res=='SUCCESS') {
            window.location.reload();
        }
        else {
            alert('Error in attaching file ----'+ res);
        }
    }
    catch(er) {
        alert(er);
    }
}

4. Upload the js file in static resource section with name = "SaveQuoteAsCustomPDF".
5. After upload done click on view and copy the url from browser.
6. Now create a custom button under Quote section in setup with following configurations
6.1: "Display Type" = "Detail Page"
6.2: "Behavior" = "Execute JavaScript"
6.3: "Content Source" = "OnClick JavaScript"
6.4: Put the following contents in the box below:

{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")}
{!REQUIRESCRIPT("/resource/1470022474000/SaveQuoteAsCustomPDF")} /* Location from step 5 */

var pdfOverlay = QuotePDFPreview.quotePDFObjs['quotePDFOverlay'];
pdfOverlay.dialog.buttonContents = '<input value=\"Save Quote As PDF\"  class=\"btn\" name=\"save\" onclick=\"SaveQuoteAsCustomPDF(\'{!Quote.Id}\');\" title=\"Save Quote As PDF\" type=\"button\" /><input value=\"Close\"  class=\"btn\" name=\"cancel\" onclick=\"QuotePDFPreview.getQuotePDFObject(\'quotePDFOverlay\').close();\" title=\"Close\" type=\"button\" />';

pdfOverlay.setSavable(true);
pdfOverlay.setPDFContents('/apex/QuoteCustomPdfView?Id={!Quote.Id}',null,null);
pdfOverlay.display();

7. Add the button in quote page layout.
8. View details of a quote & click the button you added on step 7.

Sunday, May 17, 2015

Concat Or Join Or Add Two Or More Pdf File To One Pdf FIle Using Java & Lowagie


package com.pkm.concat.two.pdf;

import java.io.*;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

/**
 * Created by pritom on 17/05/2015.
 */
public class ConcatTwoPdfBytes {
    public static void main(String[] args) throws Exception {
        File file = new File("from-1.pdf");
        FileInputStream fileInputStream = new FileInputStream(file);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        Document document = new Document();
        Rectangle rectangle = PageSize.A4;
        document.setPageSize(rectangle);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, byteArrayOutputStream);
        document.open();
        PdfContentByte cb = pdfWriter.getDirectContent();

        PdfReader pdfReader = new PdfReader(fileInputStream);
        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, i);
            cb.addTemplate(page, 0, 0);
        }

        File file2 = new File("from-2.pdf");
        fileInputStream = new FileInputStream(file2);
        pdfReader = new PdfReader(fileInputStream);
        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, i);
            cb.addTemplate(page, 0, 0);
        }
        document.close();

        byte[] bytesRead = byteArrayOutputStream.toByteArray();
        File outputFile = new File(file.getName() + " And  " + file2.getName());
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        fileOutputStream.write(bytesRead);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}


from-1.pdf from-2.pdf from-1.pdf And from-2.pdf Download Jar