【发布时间】:2019-06-08 16:52:02
【问题描述】:
我正在尝试使用 java 将包含多个图像的二进制文件转换为 pdf 文档,使用 itextpdf 是我以正确格式获得转换文件的唯一解决方案,但这里的问题是输出它只为我提供了一个图像(第一个),而丢失了二进制文件中的其他图像。
我已经证明可以使用 itextpdf 在文档中添加图像以及其他一些解决方案,例如:
https://www.mkyong.com/java/how-to-convert-array-of-bytes-into-file/
或
create pdf from binary data in java
据我了解,我的问题是我已经读取了我的二进制文件并将它们存储在一个字节 [] 中,并且在我将文件的内容传递给 Vector 之后,
我创建了一个函数,它作为参数 Vector 并创建了一个包含图像的 pdf,问题是它只在 pdf 中插入第一个图像,因为它不能在 Vector 内分离第一个图像的结尾在这种情况下,图像和第二张图像的开头(JPEG 图像文件以 FF D8 开头,以 FF D9 结尾。):
How to identify contents of a byte[] is a jpeg?
File imgFront = new File("C:/Users/binaryFile");
byte[] fileContent;
Vector<byte[]> records = new Vector<byte[]>();
try {
fileContent = Files.readAllBytes(imgFront.toPath());
records.add(fileContent); // add the result on Vector<byte[]>
} catch (IOException e1) {
System.out.println( e1 );
}
...
public static String ImageToPDF(Vector<byte[]> imageVector, String pathFile) {
String FileoutputName = pathFile + ".pdf";
Document document = null;
try {
FileOutputStream fos = new FileOutputStream(FileoutputName );
PdfWriter writer = PdfWriter.getInstance(document, fos);
writer.open();
document.open();
//loop here the ImageVector in order to get one by one the images,
//but I get only the first one
for (byte[] img : imageVector) {
Image image = Image.getInstance(img);
image.scaleToFit(500, 500); //size
document.add(image);
}
document.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
return FileoutputName ;
}
我希望在 pdf 中包含所有图像,而不仅仅是一个。
【问题讨论】:
-
请遵循 Java 编码指南以避免混淆我们。方法名称、参数名称、字段名称和变量名称都应以小写字母开头。当我们看到一个以大写字母开头的名字时,我们认为它是一个类名。这让你的代码更难理解。
-
该二进制文件是如何创建的?
-
是的,谢谢你提到这一点。我不确定这个文件是如何创建的,因为他们给我发送了一个包含 100 个二进制文件的文件夹,其中一些文件里面有一个图像,而另一些则不止一个。我试图检查咬合输出以确定他们使用的是哪种图像,png、jpg、tiff 等。我发现文件以 77、77、42 开头,意思是 TIFF 图像sparkhound.com/blog/detect-image-file-types-through-byte-arrays,并尝试从该点开始解决。
标签: java arrays binaryfiles