Как я могу преобразовать файл PNG в PDF, используя Java? - PullRequest
5 голосов
/ 02 декабря 2011

Есть ли какие-нибудь библиотеки с открытым исходным кодом, которые я могу использовать?

Ответы [ 3 ]

9 голосов
/ 03 декабря 2011

itext может помочь вам.Вы действительно не конвертируете png в pdf, но создаете pdf с png в нем.простой пример:

Document document = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.getInstance(document, new FileOutputStream("C:/test.pdf"));
document.open();
Image image = Image.getInstance(getClass().getResource("/logo.png"));
document.add(image);
document.close();
3 голосов
/ 21 марта 2017

Пример, который поворачивает страницу, если альбомный режим подходит лучше

/**
 * Converts arbitrary image file to PDF
 * http://stackoverflow.com/a/42937466/241986
 * @param imageFile contents of JPEG or PNG file
 * @param outputStream stream to write out pdf, always closed after this method execution.
 * @throws IOException when there' an actual exception or image is not valid
 */
public static void imageToPdf(byte[] imageFile, OutputStream outputStream) throws IOException {
    try {
        Image image;
        try {
            image = Image.getInstance(imageFile);
        } catch (BadElementException bee) {
            throw new IOException(bee);
        }

        //See http://stackoverflow.com/questions/1373035/how-do-i-scale-one-rectangle-to-the-maximum-size-possible-within-another-rectang
        Rectangle A4 = PageSize.A4;

        float scalePortrait = Math.min(A4.getWidth() / image.getWidth(),
                A4.getHeight() / image.getHeight());

        float scaleLandscape = Math.min(A4.getHeight() / image.getWidth(),
                A4.getWidth() / image.getHeight());

        // We try to occupy as much space as possible
        // Sportrait = (w*scalePortrait) * (h*scalePortrait)
        // Slandscape = (w*scaleLandscape) * (h*scaleLandscape)

        // therefore the bigger area is where we have bigger scale
        boolean isLandscape = scaleLandscape > scalePortrait;

        float w;
        float h;
        if (isLandscape) {
            A4 = A4.rotate();
            w = image.getWidth() * scaleLandscape;
            h = image.getHeight() * scaleLandscape;
        } else {
            w = image.getWidth() * scalePortrait;
            h = image.getHeight() * scalePortrait;
        }

        Document document = new Document(A4, 10, 10, 10, 10);

        try {
            PdfWriter.getInstance(document, outputStream);
        } catch (DocumentException e) {
            throw new IOException(e);
        }
        document.open();
        try {
            image.scaleAbsolute(w, h);
            float posH = (A4.getHeight() - h) / 2;
            float posW = (A4.getWidth() - w) / 2;

            image.setAbsolutePosition(posW, posH);
            image.setBorder(Image.NO_BORDER);
            image.setBorderWidth(0);

            try {
                document.newPage();
                document.add(image);
            } catch (DocumentException de) {
                throw new IOException(de);
            }
        } finally {
            document.close();
        }
    } finally {
        outputStream.close();
    }
}

Внутри pom.xml, одной из бесплатных вилок iText, если вы еще не используете iText

<dependency>
    <groupId>com.github.librepdf</groupId>
    <artifactId>openpdf</artifactId>
    <version>1.0.1</version>
</dependency>
0 голосов
/ 03 декабря 2011

для чтения javax.imageio.ImageIO для написания pdf itext: http://itextpdf.com

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...