如何使用java将PNG文件转换为PDF?[已关闭]

syqv5f0l  于 2023-01-19  发布在  Java
关注(0)|答案(5)|浏览(193)

**已关闭。**此问题不符合Stack Overflow guidelines。当前不接受答案。

我们不允许问题寻求有关书籍、工具、软件库等的推荐。你可以编辑问题,以便可以使用事实和引用来回答问题。
2天前关闭。
Improve this question
有没有我可以使用的开源库?

2wnc66cl

2wnc66cl1#

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();
tag5nh1u

tag5nh1u2#

一个旋转页面的示例,如果横向模式更适合

/**
 * 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>
kupeojn6

kupeojn63#

使用iText将jpg/png/gif格式转换为pdf格式,代码如下。

import java.io.FileOutputStream;
//com.lowagie...   old version
//com.itextpdf...  recent version
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Image;

public class ImageToPDF {
  public static void main(String ... args) {
    Document document = new Document();
    String input = "c:/temp/capture.png"; // .gif and .jpg are ok too!
    String output = "c:/temp/capture.pdf";
    try {
      FileOutputStream fos = new FileOutputStream(output);
      PdfWriter writer = PdfWriter.getInstance(document, fos);
      writer.open();
      document.open();
      document.add(Image.getInstance(input));
      document.close();
      writer.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}
mitkmikd

mitkmikd4#

用于阅读javax.imageio.ImageIO用于编写pdf itext:http://itextpdf.com

vvppvyoh

vvppvyoh5#

为了简单起见,带有PNG或JPEG的现代网页可以通过命令行转换为单页或多页PDF。
通过放置一个图像在默认的宽度或高度,或设置为保持在任何比例,它只需要几行命令行文本输出一个PDF。非常容易模板在一个简单的记事本或复杂的IDE。
对于转换chrome -headless可以更快地为一页比释放回车键,它需要更长的时间为4000张图片。
其他库可以作为后期处理用于更复杂的操作,但是Chrome只会生成一个非常好的默认媒体页面,除非添加额外的CSS。
因此从控制台或其他编辑器回显以下内容

<HTML>
<image src="01.jpg" width="100%" />
<image src="02.jpg" width="100%" />
</HTML>

运行相当于的Java shell
"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --headless --print-to-pdf="C:\Data\out.pdf" C:/Data/htm.htm

结果

相关问题