一张图片转pdf
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class ImgToPdf {
public static void main(String[] args) {
try {
String outPath = "pdf.pdf";
Image instance = Image.getInstance("C:\\Users\\Administrator\\Desktop\\QQ截图20220624140018.png");
float pageWidth = instance.getWidth();
float pageHeight = instance.getHeight();
Document document = new Document(new Rectangle(pageWidth, pageHeight));
FileOutputStream outputStream = new FileOutputStream(outPath);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
writer.setPdfVersion(PdfWriter.VERSION_1_5);
document.open();
PdfContentByte cb = writer.getDirectContent();
cb.addImage(instance,pageWidth,0,0,pageHeight,0,0);
outputStream.flush();
document.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
多张图片转pdf
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
public class ImgToPdf {
public static void main(String[] args) {
List<String> listImg = new ArrayList<String>();
listImg.add("C:\\Users\\Administrator\\Desktop\\QQ截图20220624140018.png");
listImg.add("C:\\Users\\Administrator\\Desktop\\QQ截图20220624140844.png");
try {
String outPath = "pdf.pdf";
Image instance = Image.getInstance(listImg.get(0));
float pageWidth = instance.getWidth();
float pageHeight = instance.getHeight();
Document document = new Document(new Rectangle(pageWidth, pageHeight));
FileOutputStream outputStream = new FileOutputStream(outPath);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
writer.setPdfVersion(PdfWriter.VERSION_1_5);
document.open();
PdfContentByte cb = writer.getDirectContent();
cb.addImage(instance,pageWidth,0,0,pageHeight,0,0);
for(int i=1;i<listImg.size();i++){
Image instance2 = Image.getInstance(listImg.get(i));
float pageWidth2= instance2.getWidth();
float pageHeight2 = instance2.getHeight();
document.setPageSize(new Rectangle(pageWidth2,pageHeight2));
document.newPage();
cb.addImage(instance2,pageWidth2,0,0,pageHeight2,0,0);
}
outputStream.flush();
document.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}