How to Reduce Pdf File Size in Javascript

You may have heard information about the enormous benefits of using PDF files for your business content and that it can help your business grow. You certainly understand how important it is to create a professional and attractive-looking set of customized PDFs that are easily accessible, searchable and sharable.

Converting a Pdf document or image to a smaller format comes with some benefits and some downsides. The original file will lose any type of formatting, the original vba macros will not be converted to pdf macros, and if the original file was password protected then it will remain password protected when you convert the document back to Pdf again.

If you have been around the SEO world for some time now, then it is no secret that search engines like Google are continuously changing their systems and algorithms to better serve users. To become more specific, they are making it harder for spam to get through. You need to be an on-point content creator, use creative keywords and find ways to get your audience keep clicking. This can include getting your audience to share a certain web page or having them sign up for something.

Due to the secure and shareable nature of the PDF, it has become a favorite format for larger documents such as contracts. However, if you attempt to email these substantial documents, you can run into issues with file size; to solve these issues, the following API can be run in JavaScript to reduce the file size and optimize the content of a PDF.

Compress PDF with Adobe Acrobat or Nitro

Whether you are using Adobe Acrobat or Nitro PDF Professional, you can reduce PDF size in a simple, yet highly effective way. The “Save” feature is often much faster than the “Save As”, simply because any additional changes to the file are appended at the end of the file, without a complete rewrite, so a bulk of info is just adding up. Instead, by using the “Save As” feature, you can forget about this and reduce PDF size.

All you have to do is:

  1. Open the PDF editor
  2. In Acrobat go to File Save As – Click Save once again
  3. In Nitro PDF Professional go to File Save As – Choose the file you want to compress – Click Save

Remove unwanted objects from PDF files

There are many features that can help you decrease the size of your PDF files. Some of the best tools are Adobe and Nitro PDF. The size of a PDF file is increased by links, bookmarks, form fields, and JavaScript. But this shouldn’t be an issue. Whether you use the Nitro PDF Professional or Adobe, just follow the steps below. They’ll surely help you reduce PDF size:

  1. Open the PDF in the PDF editor
  2. In Nitro PDF Professional: Go to File > Optimize PDF > Click CustomNitro Optimize PDF
  3. In Acrobat: Go to File > Save as other > Optimized PDF. More details here
  4. Choose the objects to removePDF Optimizer - Remove unwanted objects
  5. Press OK to complete

Clear unused space – Use the PDF Optimizer

There is unused space on your PDF that you might not be aware of. It’s always better to know what pulls up the size of your file. Getting rid of the unused space is often the easiest way to reduce PDF size. If you are using Adobe, then you should follow these simple steps:

  1. Select Tools > Advanced Optimization
  2. Click on PDF Optimizer
  3. Select the Audit Space Usage

Colors can be a problem in a file size

If the color is not your major concern, don’t let the color scheme interfere with the file size. Use the RGB color space instead of the CMYK, and you will see a significant change. You can find it easily in the Adobe Acrobat Pro options menu bar. Here’s how to do it:

  1. Open the PDF in Adobe Acrobat Pro
  2. Choose Tools > Print Production > Convert Colors
  3. Select the RGB color space
  4. Select the FOGRA39 profile (this is a print industry standard)
  5. Check which pages you would like to convertReduce PDF size - Colors can be a problem in a file size
  6. Click OK and you’re done
ALSO READ:   Python for Middle Schoolers

The first step is to install the jQuery library like so:

bower install jquery

With the installation out of the way, we are ready to call the function with the following code:

var form = new FormData();
form.append("inputFile", fileInput.files[0], "file");var settings = {
"url": "https://api.cloudmersive.com/convert/edit/pdf/optimize/reduce-file-size",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "multipart/form-data",
"Apikey": "YOUR-API-KEY-HERE"
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};$.ajax(settings).done(function (response) {
console.log(response);
});

This will return a downloadable PDF file that’s ready for use wherever you need it. To retrieve your personal API key, head to the Cloudmersive website to register for a free account.

Compress & optimize PDF files in JavaScript

More languages

Sample JavaScript code for using PDFTron SDK to reduce PDF file size by removing redundant information and compressing data streams using the latest in image compression technology. Learn more about our JavaScript PDF Library.Get StartedSamplesDownload

To run this sample, get started with a free trial of PDFTron SDK.

//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

//---------------------------------------------------------------------------------------
// The following sample illustrates how to reduce PDF file size using 'pdftron.PDF.Optimizer'.
// The sample also shows how to simplify and optimize PDF documents for viewing on mobile devices 
// and on the Web using 'pdftron.PDF.Flattener'.
//
// @note Both 'Optimizer' and 'Flattener' are separately licensable add-on options to the core PDFNet license.
//
// ----
//
// 'pdftron.PDF.Optimizer' can be used to optimize PDF documents by reducing the file size, removing 
// redundant information, and compressing data streams using the latest in image compression technology. 
//
// PDF Optimizer can compress and shrink PDF file size with the following operations:
// - Remove duplicated fonts, images, ICC profiles, and any other data stream. 
// - Optionally convert high-quality or print-ready PDF files to small, efficient and web-ready PDF. 
// - Optionally down-sample large images to a given resolution. 
// - Optionally compress or recompress PDF images using JBIG2 and JPEG2000 compression formats. 
// - Compress uncompressed streams and remove unused PDF objects. 
//
// ----
//
// 'pdftron.PDF.Flattener' can be used to speed-up PDF rendering on mobile devices and on the Web by 
// simplifying page content (e.g. flattening complex graphics into images) while maintaining vector text 
// whenever possible.
//
// Flattener can also be used to simplify process of writing custom converters from PDF to other formats. 
// In this case, Flattener can be used as first step in the conversion pipeline to reduce any PDF to a 
// very simple representation (e.g. vector text on top of a background image).
//---------------------------------------------------------------------------------------

const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {
  'use strict';

  exports.runOptimizerTest = () => {
    const main = async () => {
      const inputPath = '../TestFiles/';
      const outputPath = inputPath + 'Output/';
      const inputFilename = 'newsletter';

      // The first step in every application using PDFNet is to initialize the 
      // library and set the path to common PDF resources. The library is usually 
      // initialized only once, but calling Initialize() multiple times is also fine.

      //--------------------------------------------------------------------------------
      // Example 1) Simple optimization of a pdf with default settings. 
      //
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
        await doc.initSecurityHandler();
        await PDFNet.Optimizer.optimize(doc);
        doc.save(outputPath + inputFilename + '_opt1.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
      }
      catch (err) {
        console.log(err);
      }

      //--------------------------------------------------------------------------------
      // Example 2) Reduce image quality and use jpeg compression for
      // non monochrome images.
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
        await doc.initSecurityHandler();
        const image_settings = new PDFNet.Optimizer.ImageSettings();

        // low quality jpeg compression
        image_settings.setCompressionMode(PDFNet.Optimizer.ImageSettings.CompressionMode.e_jpeg);
        image_settings.setQuality(1);

        // Set the output dpi to be standard screen resolution
        image_settings.setImageDPI(144, 96);

        // this option will recompress images not compressed with
        // jpeg compression and use the result if the new image
        // is smaller.
        image_settings.forceRecompression(true);

        // this option is not commonly used since it can 
        // potentially lead to larger files. It should be enabled
        // only if the output compression specified should be applied
        // to every image of a given type regardless of the output image size
        //image_settings.forceChanges(true);

        const opt_settings = new PDFNet.Optimizer.OptimizerSettings();
        opt_settings.setColorImageSettings(image_settings);
        opt_settings.setGrayscaleImageSettings(image_settings);

        // use the same settings for both color and grayscale images
        await PDFNet.Optimizer.optimize(doc, opt_settings);

        doc.save(outputPath + inputFilename + '_opt2.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
      }
      catch (err) {
        console.log(err);
      }

      //--------------------------------------------------------------------------------
      // Example 3) Use monochrome image settings and default settings
      // for color and grayscale images. 
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
        await doc.initSecurityHandler();

        const mono_image_settings = new PDFNet.Optimizer.MonoImageSettings();

        mono_image_settings.setCompressionMode(PDFNet.Optimizer.MonoImageSettings.CompressionMode.e_jbig2);
        mono_image_settings.forceRecompression(true);

        const opt_settings = new PDFNet.Optimizer.OptimizerSettings();

        opt_settings.setMonoImageSettings(mono_image_settings);

        await PDFNet.Optimizer.optimize(doc, opt_settings);
        doc.save(outputPath + inputFilename + '_opt3.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
      }
      catch (err) {
        console.log(err);
      }

      // ----------------------------------------------------------------------
      // Example 4) Use Flattener to simplify content in this document
      // using default settings
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'TigerText.pdf');
        await doc.initSecurityHandler();

        const fl = await PDFNet.Flattener.create();

        // The following lines can increase the resolution of background
        // images.
        //fl.setDPI(300);
        //fl.setMaximumImagePixels(5000000);

        // This line can be used to output Flate compressed background
        // images rather than DCTDecode compressed images which is the default
        //fl.setPreferJPG(false);

        // In order to adjust thresholds for when text is Flattened
        // the following function can be used.
        //fl.setThreshold(PDFNet.Flattener.Threshold.e_keep_most);

        // We use e_fast option here since it is usually preferable
        // to avoid Flattening simple pages in terms of size and 
        // rendering speed. If the desire is to simplify the 
        // document for processing such that it contains only text and
        // a background image e_simple should be used instead.
        await fl.process(doc, PDFNet.Flattener.Mode.e_fast);

        doc.save(outputPath + 'TigerText_flatten.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
      }
      catch (err) {
        console.log(err);
      }

      //--------------------------------------------------------------------------------
      // Example 5) Optimize a PDF for viewing using SaveViewerOptimized.
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename + '.pdf');
        doc.initSecurityHandler();

        const opts = new PDFNet.PDFDoc.ViewerOptimizedOptions();

        // set the maximum dimension (width or height) that thumbnails will have.
        opts.setThumbnailSize(1500);

        // set thumbnail rendering threshold. A number from 0 (include all thumbnails) to 100 (include only the first thumbnail) 
        // representing the complexity at which SaveViewerOptimized would include the thumbnail. 
        // By default it only produces thumbnails on the first and complex pages. 
        // The following line will produce thumbnails on every page.
        // opts.setThumbnailRenderingThreshold(0); 

        await doc.saveViewerOptimized(outputPath + inputFilename + '_SaveViewerOptimized.pdf', opts);
      }
      catch (err) {
        console.log(err);
      }
    };
    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) {
      console.log('Error: ' + JSON.stringify(error));
    }).then(function () { return PDFNet.shutdown(); });
  };
  exports.runOptimizerTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=OptimizerTest.js

How to compress PDFs

1. Reduce PDF file size by compressing the PDF

The idea of recreating a PDF sounds scary. With Nitro PDF Pro, you can shrink PDF files down by simply compressing the document. This allows you to strip out any unwanted space-gobbling objects, remove tags, and compress any pesky images further. Any tool that supports ‘print to PDF’ functionality can be used for this trick, including Nitro PDF Pro.

  1. Open the PDF file in Nitro PDF Pro
  2. Click File > Print
  3. Select Nitro PDF Creator from the list of printers
  4. Click the Properties button and select Web-ready Conversion Quality
  5. Click OK.
ALSO READ:   Best Programming Language for Beginners 2019
Reduce-PDF-file-size.png

Find out how six companies are achieving digital transformation success with Nitro Pro>>

2. Make PDF smaller with ‘Save As’

If you use a PDF editor such as Nitro PDF Pro you can make use of the ‘Save As’ functionality to trim some fat off your PDF files. This method was explained succinctly in a previous post:

PDF files have something that is called incremental updates, where any changes that you make to a document are appended to the end of the file without doing a complete rewrite. This is why the Save feature is much faster than a Save As, and also why PDF files saved this way can be large. The ‘Save As’ feature will rewrite the entire file and provide you with a smaller file size.

Here’s how to shrink PDF file size using the ‘Save As’ method:

  1. Open the PDF in your Nitro Pro editor
  2. Click File > Save As

3. Decrease PDF file size by removing unwanted objects

PDF files can contain different “objects,” like bookmarks, links, annotations, form fields, JavaScript, named destinations and embedded fonts—all of which can be removed to make PDFs smaller. Like tip #2, this method requires a PDF editing tool such as Nitro Pro.

  1. Open the PDF in Nitro Pro
  2. Click File > Optimize PDF 
  3. In the Optimize PDF dialogselect Reduced size > Show Details
  4. Choose the objects to remove
  5. Click OK, then Optimize  
Optimize-2.png

4. Minimize PDF file size by shrinking all images

For PDF files that contain many images, downsizing all of them can make a noticeable difference in making your PDF smaller. Following the same instructions as Step 3 will get you where you need to go!

Conclusion

Pdf is a file format which is used for documents, reports and presentations. An Adobe pdf file can be generated from any application. It comes with a wide range of benefits like a nice way to display documents (e.g. no Word formatting issues), the ability for end users to edit the files, control of font and colors and much more. There are times when you want to generate a pdf from files that don’t exist in the PDF format, so you will need a converter tool first.

ALSO READ:   Best IDE for Web Development

Compressing a PDF file is an excellent way to increase efficiency when sending large documents via email. It is possible to compress a PDF file with Javascript or CSS

Leave a Comment