1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java圧縮PDFドキュメント

Posted at

この文はJavaでPDF文書を圧縮する方法を以下の二つの面から紹介します。
•文書の内容を圧縮する
•ドキュメントの画像を圧縮する

文書の内容を圧縮する:

import com.spire.pdf.*;

public class CompressPDF {
    public static void main(String[] args) {
        String inputFile = "Sample.pdf";
        String outputFile = "output/CompressPDFcontent.pdf";

        PdfDocument document = new PdfDocument();
        document.loadFromFile(inputFile);

        document.getFileInfo().setIncrementalUpdate(false);
        document.setCompressionLevel(PdfCompressionLevel.Best);

        document.saveToFile(outputFile, FileFormat.PDF);
        document.close();
        }
    }

Compress PDF content.png

ドキュメントの画像を圧縮する

まず、元のPDF文書の画像を抽出し、画質を低下させることで、画像を小さくし、縮小された画像を元のドキュメントの画像に置き換えることで、PDF文書のサイズを低減します.

import com.spire.pdf.*;
import com.spire.pdf.exporting.PdfImageInfo;
import com.spire.pdf.graphics.PdfBitmap;

public class CompressPDF {

    public static void main(String[] args) {

        String inputFile = "Sample.pdf";
        String outputFile = "output/CompressPDFImage.pdf";

        PdfDocument document = new PdfDocument();
        document.loadFromFile(inputFile);

        document.getFileInfo().setIncrementalUpdate(false);

        for (int i = 0; i < document.getPages().getCount(); i++) {

            PdfPageBase page = document.getPages().get(i);
            PdfImageInfo[] images = page.getImagesInfo();
            if (images != null && images.length > 0)
                for (int j = 0; j < images.length; j++) {
                    PdfImageInfo image = images[j];
                    PdfBitmap bp = new PdfBitmap(image.getImage());
                    bp.setQuality(20);
                    page.replaceImage(j, bp);

                }
        }
        document.saveToFile(outputFile, FileFormat.PDF);
        document.close();
    }
}

Compress PDF image.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?