001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (https://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software, please see the
018 * company website: https://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: https://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.pdftools;
029
030import org.opencms.loader.CmsImageScaler;
031import org.opencms.main.OpenCms;
032import org.opencms.util.CmsFileUtil;
033
034import java.awt.Color;
035import java.awt.Graphics2D;
036import java.awt.geom.AffineTransform;
037import java.awt.image.AffineTransformOp;
038import java.awt.image.BufferedImage;
039import java.io.File;
040import java.io.InputStream;
041
042import org.apache.commons.io.output.ByteArrayOutputStream;
043import org.apache.pdfbox.tools.imageio.ImageIOUtil;
044
045import org.jpedal.PdfDecoder;
046import org.jpedal.fonts.FontMappings;
047import org.jpedal.objects.PdfPageData;
048
049/**
050 * Class for generating thumbnails from PDF documents using the PDFBox library.<p>
051 */
052public class CmsPdfThumbnailGenerator {
053
054    /** A multiplier used for the input to calculateDimensions. */
055    private static final int FAKE_PIXEL_MULTIPLIER = 10000;
056
057    static {
058        FontMappings.setFontReplacements();
059    }
060
061    /**
062     * Generates the image data for a thumbnail from a PDF.<p>
063     *
064     * The given width and height determine the box in which the thumbnail should fit.
065     * The resulting image will always have these dimensions, even if the aspect ratio of the actual PDF
066     * page is different from the ratio of the given width and height. In this case, the size of the rendered
067     * page will be reduced, and the rest of the image will be filled with blank space.<p>
068     *
069     * If one of width or height is negative, then that dimension is chosen so the resulting aspect ratio is the
070     * aspect ratio of the PDF page.
071     *
072     * @param pdfInputStream the input stream for reading the PDF data
073     * @param boxWidth the width of the box in which the thumbnail should fit
074     * @param boxHeight the height of the box in which the thumbnail should fit
075     * @param imageFormat the image format (png, jpg, gif)
076     * @param pageIndex the index of the page for which to render the thumbnail (starting at 0)
077     *
078     * @return the image data for the thumbnail, in the given image format
079     * @throws Exception if something goes wrong
080     */
081    public byte[] generateThumbnail(
082        InputStream pdfInputStream,
083        int boxWidth,
084        int boxHeight,
085        String imageFormat,
086        int pageIndex)
087    throws Exception {
088
089        org.jpedal.io.ObjectStore.temp_dir = CmsFileUtil.normalizePath(
090            OpenCms.getSystemInfo().getWebInfRfsPath() + CmsPdfThumbnailCache.PDF_CACHE_FOLDER + File.separatorChar);
091        PdfDecoder decoder = new PdfDecoder(true);
092
093        try {
094            decoder.openPdfFileFromInputStream(pdfInputStream, false);
095            int numPages = decoder.getPageCount();
096            if (pageIndex >= numPages) {
097                pageIndex = numPages - 1;
098            } else if (pageIndex < 0) {
099                pageIndex = 0;
100            }
101
102            // width/height are in points (1/72 of an inch)
103            PdfPageData pageData = decoder.getPdfPageData();
104            double aspectRatio = (pageData.getCropBoxWidth(1 + pageIndex) * 1.0)
105                / pageData.getCropBoxHeight(1 + pageIndex);
106            int rotation = pageData.getRotation(1 + pageIndex);
107            if ((rotation == 90) || (rotation == 270)) {
108                // landscape
109                aspectRatio = 1 / aspectRatio;
110            }
111
112            if ((boxWidth < 0) && (boxHeight < 0)) {
113                throw new IllegalArgumentException("At least one of width / height must be positive!");
114            } else if ((boxWidth < 0) && (boxHeight > 0)) {
115                boxWidth = (int)Math.round(aspectRatio * boxHeight);
116            } else if ((boxWidth > 0) && (boxHeight < 0)) {
117                boxHeight = (int)Math.round(boxWidth / aspectRatio);
118            }
119
120            // calculateDimensions only takes integers, but only their ratio matters, we multiply the box width with a big number
121            int fakePixelWidth = (int)(FAKE_PIXEL_MULTIPLIER * aspectRatio);
122            int fakePixelHeight = (FAKE_PIXEL_MULTIPLIER);
123            int[] unpaddedThumbnailDimensions = CmsImageScaler.calculateDimension(
124                fakePixelWidth,
125                fakePixelHeight,
126                boxWidth,
127                boxHeight);
128            decoder.decodePage(1 + pageIndex);
129            BufferedImage pageImage = decoder.getPageAsImage(1 + pageIndex);
130            BufferedImage paddedImage = new BufferedImage(boxWidth, boxHeight, BufferedImage.TYPE_3BYTE_BGR);
131
132            Graphics2D g = paddedImage.createGraphics();
133            int uw = unpaddedThumbnailDimensions[0];
134            int uh = unpaddedThumbnailDimensions[1];
135
136            // Scale to fit in  the box
137            AffineTransformOp op = new AffineTransformOp(
138                AffineTransform.getScaleInstance((uw * 1.0) / pageImage.getWidth(), (uh * 1.0) / pageImage.getHeight()),
139                AffineTransformOp.TYPE_BILINEAR);
140
141            g.setColor(Color.WHITE);
142            // Fill box image with white, then draw the image data for the PDF in the middle
143            g.fillRect(0, 0, paddedImage.getWidth(), paddedImage.getHeight());
144            //g.drawImage(pageImage, (boxWidth - pageImage.getWidth()) / 2, (boxHeight - pageImage.getHeight()) / 2, null);
145            g.drawImage(pageImage, op, (boxWidth - uw) / 2, (boxHeight - uh) / 2);
146            BufferedImage pageThumbnail = paddedImage;
147            ByteArrayOutputStream out = new ByteArrayOutputStream();
148            ImageIOUtil.writeImage(pageThumbnail, imageFormat, out);
149            byte[] imageData = out.toByteArray();
150            return imageData;
151        } finally {
152            if (decoder.isOpen()) {
153                decoder.closePdfFile();
154            }
155            pdfInputStream.close();
156
157        }
158    }
159}