PDFKit: A JavaScript PDF Generation Library for Node and The Browser

PDFKit

A JavaScript PDF generation library for Node and the browser.

Installation

Installation uses the npm package manager. Just type the following command after installing npm.

npm install pdfkit

Features

  • Vector graphics
    • HTML5 canvas-like API
    • Path operations
    • SVG path parser for easy path creation
    • Transformations
    • Linear and radial gradients
  • Text
    • Line wrapping
    • Text alignments
    • Bulleted lists
  • Font embedding
    • Supports TrueType (.ttf), OpenType (.otf), WOFF, WOFF2, TrueType Collections (.ttc), and Datafork TrueType (.dfont) fonts
    • Font subsetting
    • See fontkit for more details on advanced glyph layout support.
  • Image embedding
    • Supports JPEG and PNG files (including indexed PNGs, and PNGs with transparency)
  • Annotations
    • Links
    • Notes
    • Highlights
    • Underlines
    • etc.
  • AcroForms
  • Outlines
  • PDF security
    • Encryption
    • Access privileges (printing, copying, modifying, annotating, form filling, content accessibility, document assembly)
  • Accessibility support (marked content, logical structure, Tagged PDF, PDF/UA)

Coming soon!

  • Patterns fills
  • Higher level APIs for creating tables and laying out content
  • More performance optimizations
  • Even more awesomeness, perhaps written by you! Please fork this repository and send me pull requests.

Example

const PDFDocument = require('pdfkit');
const fs = require('fs');

// Create a document
const doc = new PDFDocument();

// Pipe its output somewhere, like to a file or HTTP response
// See below for browser usage
doc.pipe(fs.createWriteStream('output.pdf'));

// Embed a font, set the font size, and render some text
doc
  .font('fonts/PalatinoBold.ttf')
  .fontSize(25)
  .text('Some text with an embedded font!', 100, 100);

// Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('path/to/image.png', {
  fit: [250, 300],
  align: 'center',
  valign: 'center'
});

// Add another page
doc
  .addPage()
  .fontSize(25)
  .text('Here is some vector graphics...', 100, 100);

// Draw a triangle
doc
  .save()
  .moveTo(100, 150)
  .lineTo(100, 250)
  .lineTo(200, 250)
  .fill('#FF3300');

// Apply some transforms and render an SVG path with the 'even-odd' fill rule
doc
  .scale(0.6)
  .translate(470, -380)
  .path('M 250,75 L 323,301 131,161 369,161 177,301 z')
  .fill('red', 'even-odd')
  .restore();

// Add some text with annotations
doc
  .addPage()
  .fillColor('blue')
  .text('Here is a link!', 100, 100)
  .underline(100, 100, 160, 27, { color: '#0000FF' })
  .link(100, 100, 160, 27, 'http://google.com/');

// Finalize PDF file
doc.end();

The PDF output from this example (with a few additions) shows the power of PDFKit — producing complex documents with a very small amount of code. For more, see the demo folder and the PDFKit programming guide.

Browser Usage

There are three ways to use PDFKit in the browser:

In addition to PDFKit, you'll need somewhere to stream the output to. HTML5 has a Blob object which can be used to store binary data, and get URLs to this data in order to display PDF output inside an iframe, or upload to a server, etc. In order to get a Blob from the output of PDFKit, you can use the blob-stream module.

The following example uses Browserify or webpack to load PDFKit and blob-stream. See here and here for examples of prebuilt version usage.

// require dependencies
const PDFDocument = require('pdfkit');
const blobStream = require('blob-stream');

// create a document the same way as above
const doc = new PDFDocument();

// pipe the document to a blob
const stream = doc.pipe(blobStream());

// add your content to the document here, as usual

// get a blob when you are done
doc.end();
stream.on('finish', function() {
  // get a blob you can do whatever you like with
  const blob = stream.toBlob('application/pdf');

  // or get a blob URL for display in the browser
  const url = stream.toBlobURL('application/pdf');
  iframe.src = url;
});

You can see an interactive in-browser demo of PDFKit here.

Note that in order to Browserify a project using PDFKit, you need to install the brfs module with npm, which is used to load built-in font data into the package. It is listed as a devDependency in PDFKit's package.json, so it isn't installed by default for Node users. If you forget to install it, Browserify will print an error message.

Documentation

For complete API documentation and more examples, see the PDFKit website.

Description

PDFKit is a PDF document generation library for Node and the browser that makes creating complex, multi-page, printable documents easy. The API embraces chainability, and includes both low level functions as well as abstractions for higher level functionality. The PDFKit API is designed to be simple, so generating complex documents is often as simple as a few function calls.

Check out some of the documentation and examples to see for yourself! You can also read the guide as a self-generated PDF with example output displayed inline. If you'd like to see how it was generated, check out the README in the docs folder.

You can also try out an interactive in-browser demo of PDFKit here.


Download Details:

Author: foliojs
Source Code: https://github.com/foliojs/pdfkit 
License: MIT license

#node #javascript #pdf 

PDFKit: A JavaScript PDF Generation Library for Node and The Browser

Add Images to a PDF Document with JavaScript

How to Add Images to a PDF Document with JavaScript

In today's video we'll have a look at how we can add images to and generate a PDF document using JavaScript on the client-side. This is very easily done using a library called jsPDF.

Get jsPDF: https://morioh.com/p/faaa76c87ba5 

#pdf #javascript

Add Images to a PDF Document with JavaScript

jsPDF: A library to Generate PDFs in JavaScript

A library to generate PDFs in JavaScript. Client-side JavaScript PDF generation for everyone.

jsPDF is now co-maintained by yWorks - the diagramming experts.

Live Demo | Documentation

Install

Recommended: get jsPDF from npm:

npm install jspdf --save
# or
yarn add jspdf

Alternatively, load it from a CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

Or always get latest version via unpkg

<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>

The dist folder of this package contains different kinds of files:

  • jspdf.es.*.js: Modern ES2015 module format.
  • jspdf.node.*.js: For running in Node. Uses file operations for loading/saving files instead of browser APIs.
  • jspdf.umd.*.js: UMD module format. For AMD or script-tag loading.
  • polyfills*.js: Required polyfills for older browsers like Internet Explorer. The es variant simply imports all required polyfills from core-js, the umd variant is self-contained.

Usually it is not necessary to specify the exact file in the import statement. Build tools or Node automatically figure out the right file, so importing "jspdf" is enough.

Usage

Then you're ready to start making your document:

import { jsPDF } from "jspdf";

// Default export is a4 paper, portrait, using millimeters for units
const doc = new jsPDF();

doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");

If you want to change the paper size, orientation, or units, you can do:

// Landscape export, 2×4 inches
const doc = new jsPDF({
  orientation: "landscape",
  unit: "in",
  format: [4, 2]
});

doc.text("Hello world!", 1, 1);
doc.save("two-by-four.pdf");

Running in Node.js

const { jsPDF } = require("jspdf"); // will automatically load the node version

const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf"); // will save the file in the current working directory

Other Module Formats

AMD

require(["jspdf"], ({ jsPDF }) => {
  const doc = new jsPDF();
  doc.text("Hello world!", 10, 10);
  doc.save("a4.pdf");
});

Globals

const { jsPDF } = window.jspdf;

const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");

Optional dependencies

Some functions of jsPDF require optional dependencies. E.g. the html method, which depends on html2canvas and, when supplied with a string HTML document, dompurify. JsPDF loads them dynamically when required (using the respective module format, e.g. dynamic imports). Build tools like Webpack will automatically create separate chunks for each of the optional dependencies. If your application does not use any of the optional dependencies, you can prevent Webpack from generating the chunks by defining them as external dependencies:

// webpack.config.js
module.exports = {
  // ...
  externals: {
    // only define the dependencies you are NOT using as externals!
    canvg: "canvg",
    html2canvas: "html2canvas",
    dompurify: "dompurify"
  }
};

In Vue CLI projects, externals can be defined via the configureWebpack or chainWebpack properties of the vue.config.js file (needs to be created, first, in fresh projects).

In Angular projects, externals can be defined using custom webpack builders.

In React (create-react-app) projects, externals can be defined by either using react-app-rewired or ejecting.

TypeScript/Angular/Webpack/React/etc. Configuration:

jsPDF can be imported just like any other 3rd party library. This works with all major toolkits and frameworks. jsPDF also offers a typings file for TypeScript projects.

import { jsPDF } from "jspdf";

You can add jsPDF to your meteor-project as follows:

meteor add jspdf:core

Polyfills

jsPDF requires modern browser APIs in order to function. To use jsPDF in older browsers like Internet Explorer, polyfills are required. You can load all required polyfills as follows:

import "jspdf/dist/polyfills.es.js";

Alternatively, you can load the prebundled polyfill file. This is not recommended, since you might end up loading polyfills multiple times. Might still be nifty for small applications or quick POCs.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/polyfills.umd.js"></script>

Use of Unicode Characters / UTF-8:

The 14 standard fonts in PDF are limited to the ASCII-codepage. If you want to use UTF-8 you have to integrate a custom font, which provides the needed glyphs. jsPDF supports .ttf-files. So if you want to have for example Chinese text in your pdf, your font has to have the necessary Chinese glyphs. So, check if your font supports the wanted glyphs or else it will show garbled characters instead of the right text.

To add the font to jsPDF use our fontconverter in /fontconverter/fontconverter.html. The fontconverter will create a js-file with the content of the provided ttf-file as base64 encoded string and additional code for jsPDF. You just have to add this generated js-File to your project. You are then ready to go to use setFont-method in your code and write your UTF-8 encoded text.

Alternatively you can just load the content of the *.ttf file as a binary string using fetch or XMLHttpRequest and add the font to the PDF file:

const doc = new jsPDF();

const myFont = ... // load the *.ttf font file as binary string

// add the font to jsPDF
doc.addFileToVFS("MyFont.ttf", myFont);
doc.addFont("MyFont.ttf", "MyFont", "normal");
doc.setFont("MyFont");

Advanced Functionality

Since the merge with the yWorks fork there are a lot of new features. However, some of them are API breaking, which is why there is an API-switch between two API modes:

  • In "compat" API mode, jsPDF has the same API as MrRio's original version, which means full compatibility with plugins. However, some advanced features like transformation matrices and patterns won't work. This is the default mode.
  • In "advanced" API mode, jsPDF has the API you're used from the yWorks-fork version. This means the availability of all advanced features like patterns, FormObjects, and transformation matrices.

You can switch between the two modes by calling

doc.advancedAPI(doc => {
  // your code
});
// or
doc.compatAPI(doc => {
  // your code
});

JsPDF will automatically switch back to the original API mode after the callback has run.

Support

Please check if your question is already handled at Stackoverflow https://stackoverflow.com/questions/tagged/jspdf. Feel free to ask a question there with the tag jspdf.

Feature requests, bug reports, etc. are very welcome as issues. Note that bug reports should follow these guidelines:

  • A bug should be reported as an mcve
  • Make sure code is properly indented and formatted (Use ``` around code blocks)
  • Provide a runnable example.
  • Try to make sure and show in your issue that the issue is actually related to jspdf and not your framework of choice.

Contributing

jsPDF cannot live without help from the community! If you think a feature is missing or you found a bug, please consider if you can spare one or two hours and prepare a pull request. If you're simply interested in this project and want to help, have a look at the open issues, especially those labeled with "bug".

You can find information about building and testing jsPDF in the contribution guide

Source: https://github.com

#pdf #javascript

jsPDF: A library to Generate PDFs in JavaScript

Flutter Plugin for Generating PDF Documents From HTML Code Templates

Usage

var htmlContent =
"""
<!DOCTYPE html>
<html>
<head>
  <style>
  table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
  }
  th, td, p {
    padding: 5px;
    text-align: left;
  }
  </style>
</head>
  <body>
    <h2>PDF Generated with flutter_html_to_pdf plugin</h2>
    <table style="width:100%">
      <caption>Sample HTML Table</caption>
      <tr>
        <th>Month</th>
        <th>Savings</th>
      </tr>
      <tr>
        <td>January</td>
        <td>100</td>
      </tr>
      <tr>
        <td>February</td>
        <td>50</td>
      </tr>
    </table>
    <p>Image loaded from web</p>
    <img src="https://i.imgur.com/wxaJsXF.png" alt="web-img">
  </body>
</html>
""";

var targetPath = "/your/sample/path";
var targetFileName = "example_pdf_file"

var generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlContent(
    htmlContent, targetPath, targetFileName);

Code above simply generates PDF file from HTML content. It should work with most of common HTML markers. You don’t need to add .pdf extension to targetFileName because plugin only generates PDF files and extension will be added automatically.

Other Usages

You can also pass File object with HTML content inside as parameter

var file = File("/sample_path/example.html");
var generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlFile(
    file, targetPath, targetFileName);

or even just path to this file

var filePath = "/sample_path/example.html";
var generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlFilePath(
    filePath, targetPath, targetFileName);

Images

If your want to add local image from device to your HTML you need to pass path to image as src value.

<img src="file:///storage/example/your_sample_image.png" alt="web-img">

or if you want to use the image File object

<img src="${imageFile.path}" alt="web-img">

Many images inside your document can significantly affect the final file size so I suggest to use flutter_image_compress plugin.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add flutter_html_to_pdf

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  flutter_html_to_pdf: ^0.7.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:flutter_html_to_pdf/flutter_html_to_pdf.dart';

example/lib/main.dart

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_full_pdf_viewer/flutter_full_pdf_viewer.dart';
import 'package:flutter_html_to_pdf/flutter_html_to_pdf.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String generatedPdfFilePath;

  @override
  void initState() {
    super.initState();
    generateExampleDocument();
  }

  Future<void> generateExampleDocument() async {
    final htmlContent = """
    <!DOCTYPE html>
    <html>
      <head>
        <style>
        table, th, td {
          border: 1px solid black;
          border-collapse: collapse;
        }
        th, td, p {
          padding: 5px;
          text-align: left;
        }
        </style>
      </head>
      <body>
        <h2>PDF Generated with flutter_html_to_pdf plugin</h2>
        
        <table style="width:100%">
          <caption>Sample HTML Table</caption>
          <tr>
            <th>Month</th>
            <th>Savings</th>
          </tr>
          <tr>
            <td>January</td>
            <td>100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>50</td>
          </tr>
        </table>
        
        <p>Image loaded from web</p>
        <img src="https://i.imgur.com/wxaJsXF.png" alt="web-img">
      </body>
    </html>
    """;

    Directory appDocDir = await getApplicationDocumentsDirectory();
    final targetPath = appDocDir.path;
    final targetFileName = "example-pdf";

    final generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlContent(htmlContent, targetPath, targetFileName);
    generatedPdfFilePath = generatedPdfFile.path;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(),
      body: Center(
        child: ElevatedButton(
          child: Text("Open Generated PDF Preview"),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => PDFViewerScaffold(appBar: AppBar(title: Text("Generated PDF Document")), path: generatedPdfFilePath)),
            );
          },
        ),
      ),
    ));
  }
}

Download details:

Author: Afur

Source: https://github.com/Afur/flutter_html_to_pdf

#flutter #html #pdf #generate #file

Flutter Plugin for Generating PDF Documents From HTML Code Templates

Spring Boot Export Data to PDF with OpenPDF

Learn to code Export PDF feature for a Spring Boot application using OpenPDF library (based on iText PDF). The users will be able to download PDF documents generated with data from database.

#springboot #pdf 

Spring Boot Export Data to PDF with OpenPDF

PyPDF2: A Utility to Read and Write PDFs with Python

PyPDF2

PyPDF2 is a pure-python PDF library capable of splitting, merging together, cropping, and transforming the pages of PDF files. It can also add custom data, viewing options, and passwords to PDF files. It can retrieve text and metadata from PDFs as well as merge entire files together.

Homepage
http://mstamy2.github.io/PyPDF2/

Examples

Please see the Sample_Code folder.

Documentation

Documentation is available at
https://pythonhosted.org/PyPDF2/

FAQ

Please see
http://mstamy2.github.io/PyPDF2/FAQ.html

Tests

PyPDF2 includes a test suite built on the unittest framework. All tests are located in the "Tests" folder. Tests can be run from the command line by:

python -m unittest Tests.tests

Download Details:

Author: mstamy2
The Demo/Documentation: View The Demo/Documentation
Download Link: Download The Source Code
Official Website: https://github.com/mstamy2/PyPDF2
License

#python #pdf 

PyPDF2: A Utility to Read and Write PDFs with Python
Joanne  Bauch

Joanne Bauch

1627793880

How to Upload and View Pdf Files in Reactjs

Hello guys in this video you can learn how you can upload and view pdf files in reactjs.

Here is the complete code

https://github.com/HamzaAnwar1998/Upload-View-Pdf-In-Reactjs

To view pdf files, I have used react-pdf-viewer. You can read about it by clicking on the url below

https://react-pdf-viewer.dev/

could’nt understand what packages to install? no worries follow these steps

1- install pdfjs library | npm install pdfjs-dist@2.6.347
2- install the core package | npm install @react-pdf-viewer/core@2.4.1
3- install pdf viewer default layout | npm install @react-pdf-viewer/default-layout
4- follow the video :)

My other popular videos

1- How to develop a simple Ecommerce Store using React and Firebase Firestore | 0- The final Project
https://www.youtube.com/watch?v=pS250LbCZfE&t=1s

2- Todo App With Vanilla JS | Separate list for every user | Using Firebase Auth & Firebase Firestore
https://www.youtube.com/watch?v=nz-f37qpADQ&t=6s

3- How to preview and upload images in Reactjs within the front end
https://www.youtube.com/watch?v=84ZkZmlhNVw

4- How to upload youtube videos in your React App without the Iframe tag or embed URL | React Player
https://www.youtube.com/watch?v=L93hyPiltLA&t=37s

Music Used in this video
(I don’t own the music and all the music credit goes to their respective owners. If you want me to remove any music, I will do that)

1- Disfigure - Blank [NCS Release]
https://www.youtube.com/watch?v=p7ZsBPK656s&list=PLqDtm0iWoNBP7xjEss5ohmFHvJ0A7Oe16

2- DEAF KEV - Invincible [NCS Release]
https://www.youtube.com/watch?v=J2X5mJ3HDYE&list=PLqDtm0iWoNBP7xjEss5ohmFHvJ0A7Oe16

3- Alan Walker - Force [NCS Release]
https://www.youtube.com/watch?v=xshEZzpS4CQ&list=PLqDtm0iWoNBP7xjEss5ohmFHvJ0A7Oe16

#reactjs #pdf

How to Upload and View Pdf Files in Reactjs
Aiyana  Miller

Aiyana Miller

1627718940

Generate Dynamic PDF in PHP : Passing Dynamic Data - Part 4

In this video series, I will show how easily you can create dynamic PDF files with PHP. It is too simple to use and find its importance in invoices, reports mailing and printing programs.

If you have any suggestions and complaints, do a shout in the comments below.

#php #pdf #dynamic

Generate Dynamic PDF in PHP : Passing Dynamic Data - Part 4
Marisol  Kuhic

Marisol Kuhic

1627707600

Flutter : PDF viewer implementation in your app | Assets, Api

#Flutter #pdf viewer implementation is explained in this part of the tutorial. Read pdf file from local folder and api following this tutorials.

Source Code : http://www.androidcoding.in/2021/02/17/flutter-pdf-viewer/

More Interesting tutorials :
Flutter Play Video on Screen Background : https://youtu.be/0AtAIH_azRs
Flutter Video Player : https://youtu.be/dXxe7E6WPUM

#pdf #app #assets #api

Flutter : PDF viewer implementation in your app | Assets, Api
Aiyana  Miller

Aiyana Miller

1627687680

Generate Dynamic PDF in PHP : Creating PDF Template - Part 3

In this video series, I will show how easily you can create dynamic PDF files with PHP. It is too simple to use and find its importance in invoices, reports mailing and printing programs.

If you have any suggestions and complaints, do a shout in the comments below.

#dynamic #pdf #php

Generate Dynamic PDF in PHP : Creating PDF Template - Part 3
Aiyana  Miller

Aiyana Miller

1627676820

Generate Dynamic PDF in PHP : Generating Simple PDF - Part 2

In this video series, I will show how easily you can create dynamic PDF files with PHP. It is too simple to use and find its importance in invoices, reports mailing and printing programs.

If you have any suggestions and complaints, do a shout in the comments below.

#pdf #php #dynamic

Generate Dynamic PDF in PHP : Generating Simple PDF - Part 2
Aiyana  Miller

Aiyana Miller

1627665900

Generate Dynamic PDF in PHP : Installing Dependencies - Part 1

In this video series, I will show how easily you can create dynamic PDF files with PHP. It is too simple to use and find its importance in invoices, reports mailing and printing programs.

If you have any suggestions and complaints, do a shout in the comments below.

#pdf #php #dynamic

Generate Dynamic PDF in PHP : Installing Dependencies - Part 1
Aiyana  Miller

Aiyana Miller

1627655040

Generate Dynamic PDF in PHP : Introduction

In this tutorial, we will see an introduction Generate Dynamic PDF in PHP

In this video series, I will show how easily you can create dynamic PDF files with PHP. It is too simple to use and find its importance in invoices, reports mailing and printing programs.

If you have any suggestions and complaints, do a shout in the comments below.

#pdf #php

Generate Dynamic PDF in PHP : Introduction

Convert PDF to Docx in Python with pdf2docx library

In this tutorial, we will dive into how we can use the pdf2docx library to convert PDF files into docx extension.

The goal of this tutorial is to develop a lightweight command-line-based utility, through Python-based modules without relying on external utilities outside the Python ecosystem in order to convert one or a collection of PDF files located within a folder.

pdf2docx is a Python library to extract data from PDF with PyMuPDF, parse layout with rules, and generate docx file with python-docx. python-docx is another library that is used by pdf2docx for creating and updating Microsoft Word (.docx) files.

#python #pdf

Convert PDF to Docx in Python with pdf2docx library
Jessica  Jacobs

Jessica Jacobs

1627417620

How to Embed PDF - HTML5 Tutorials in Hindi / Urdu

Hello friends,
In this lecture we are going to learn how to embed pdf in web page or web application. If you like the lecture please don’t forget to share and subscribe for more lectures.

#html #pdf

How to Embed PDF - HTML5 Tutorials in Hindi / Urdu