新接到一個任務,需要將原來的tif圖片轉為PDF存儲,並且需要在適合的存儲大小下保證PDF清晰度,經過整理,轉換方法分為插件和無插件兩類,
需要插件一般都借助adobe pdf,wps控件,ImageMagick軟件等,因為項目需要跨平台,所以選擇無插件方式,經過查閱資料,總結了三種:
1. 使用收費版的aspose.pdf, 功能很強大,提供了豐富API,包括PDF轉換,合成,壓縮等。
2. 使用開源的ITEXT,最新版本功能很完善,幾乎滿足所有日常需求推薦。
3. 使用Apache的pdfbox類庫
首先,使用aspose.pdf完成轉換,代碼如下:
import com.aspose.pdf.*; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; public class Convert2Pdf { //授權 public static boolean getLicense() { try { String license2 = "<License>" + " <Data>" + " <Products>" + " <Product>Aspose.Total for Java</Product>" + " <Product>Aspose.Words for Java</Product>" + " </Products>" + " <EditionType>Enterprise</EditionType>" + " <SubscriptionExpiry>20991231</SubscriptionExpiry>" + " <LicenseExpiry>20991231</LicenseExpiry>" + " <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>" + " </Data>" + " <Signature>111</Signature>" + "</License>"; InputStream is2 = new ByteArrayInputStream(license2.getBytes("UTF-8")); License asposeLic2 = new License(); asposeLic2.setLicense(is2); } catch (Exception e) { e.printStackTrace(); return false; } return true; } public static void convert(String sourcePath, String targetPath) throws IOException { //創建文檔 Document doc = new Document(); //新增一頁 Page page = doc.getPages().add(); //設置頁邊距 page.getPageInfo().getMargin().setBottom(0); page.getPageInfo().getMargin().setTop(0); page.getPageInfo().getMargin().setLeft(0); page.getPageInfo().getMargin().setRight(0); //創建圖片對象 Image image = new Image(); BufferedImage bufferedImage = ImageIO.read(new File(sourcePath)); //獲取圖片尺寸 int height = bufferedImage.getHeight(); int width = bufferedImage.getWidth(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "tif", baos); baos.flush(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); image.setImageStream(bais); //設置pdf頁的尺寸與圖片一樣 page.getPageInfo().setHeight(height); page.getPageInfo().setWidth(width); //添加圖片 page.getParagraphs().add(image); //保存 doc.save(targetPath, SaveFormat.Pdf); } public static void main(String[] args) { String source = "E:/SETUP/1.tif"; String target = "E:/SETUP/1.pdf"; if(getLicense()) { try { convert(source, target); } catch (IOException e) { e.printStackTrace(); } } } }
