PDF417码的坑
注:我這里的PDF417碼主要是用于公文,所以對格式有一定的要求,這也是為什么我這么糾結的原因了,要是沒要求那就簡單一個碼就好了(攤手)
1、 PDF417碼的生成與格式要求
先上代碼:
public static void createPdf417ForOutDoc(String text, String path) {BarcodePDF417 pdf = new BarcodePDF417();OutputStream os = null;try {pdf.setText(text.getBytes(CHARSET));byte[] buff = text.getBytes();int textLen = buff.length;// 9列數據列最長字節數為504,大于504字節數的字符串不限制長度,不然掃不出來if (textLen <= 504) {//下面兩行很重要,用于定寬 固定中間的列數為10列pdf.setOptions(BarcodePDF417.PDF417_FIXED_COLUMNS);//設置codeColumns,主要用于指定生成二維碼圖片的長度// 公文二維碼的長度一般是189px,所以我的codeColumns=7 pdf.setCodeColumns(7);//pdf.setYHeight(3F); //設置寬窄比例}Image pdfImg = pdf.createAwtImage(Color.black, Color.white);// 縮放會失真,所以不用//Image pdfImgScal = pdfImg.getScaledInstance(189, 46, Image.SCALE_REPLICATE);BufferedImage img = new BufferedImage(pdfImg.getWidth(null), 45, BufferedImage.TYPE_INT_RGB);Graphics graphics = img.getGraphics();graphics.drawImage(pdfImg, 0, 0, img.getWidth(null), img.getHeight(null), Color.white, null);os = new BufferedOutputStream(new FileOutputStream(path));ImageIO.write(img, "PNG", os);} catch (UnsupportedEncodingException e) {ExceptionLogUtil.error(null, e);} catch (FileNotFoundException e) {ExceptionLogUtil.error(null, e);} catch (IOException e) {ExceptionLogUtil.error(null, e);} finally {try {if (os != null)os.close();} catch (IOException e) {ExceptionLogUtil.error(null, e);}}}1、公文中的條形二維碼要求大家可自行上網查詢,這里主要介紹我遇到的坑。
這里使用的是開源的插件:iText-2.1.1.jar,其中使用的類是com\lowagie\text\pdf\BarcodePDF417.class
2、由于生成的碼會根據內容的多少決定碼的長高,這樣生成的碼顯然不適合插入公文,所以我對碼的格式進行了控制。通過計算,中間數據列為9列時可容納最長的字節數為504,如果超過這個限制,雖然可以生成條碼,但是掃不出來了,因為碼其實會丟失了一部分的數據,畢竟限制了人家長度還要人家給你裝這么多東西是不可能的,好在公文的標題常常是有限制的,所以我就在保證大部分碼符合要求的前提下結束了這次的折騰。
這里附上完整代碼:
2、 將生成的碼插入到偶數頁的頁腳
獲取PDF417碼生成的位置及書簽的位置
// 往文檔中插入機關公文條形二維碼 String barCode = AppUtil.getAppAbsolutePath() + outDoc.getBarCodePath(); File file = null; String filePath = AppUtil.getAppAbsolutePath() + outDoc.getWordFilePath(); file = new File(filePath); if (file.exists()) {try {Map<String, String> map = new HashMap<String, String>();map.put("barCode", barCode);Map<String, String> resultMap = Word2PdfUtil.insertImageToBookmark(filePath, map);this.setJsonString("{\"success\":\"" + resultMap.get("success") + "\"," + "\"message\":\"" + resultMap.get("msg") + "\"}");} catch (Exception e) {logger.error(null, e);this.setJsonString("{\"success\":\"false\",\"message\":\"操作失敗\"}");} }往書簽中插入圖片
package net.evecom.core.util;import java.io.*; import java.util.HashMap; import java.util.Iterator; import java.util.Map;import com.aspose.words.DocumentBuilder; import org.apache.log4j.Logger; import org.aspectj.weaver.ast.Test;import com.aspose.words.Document; import com.aspose.words.License; import com.aspose.words.SaveFormat;/*** word轉pdf* * @author* <p>* 支持doc/docx/ooxml/rtf/html/opendocument/pdf/epub/xps/swf相互轉化* </p>*/ public class Word2PdfUtil {/*** log*/private static Logger logger = Logger.getLogger(Word2PdfUtil.class);/*** 獲取證書*/public static boolean getLicense() {boolean result = false;try {// license.xml放在\WebRoot\WEB-INF\classes路徑下InputStream is = Test.class.getClassLoader().getResourceAsStream("license.xml");License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {logger.error(null, e);}return result;}/*** word轉pdf,之前pdf已存在則覆蓋掉*/public static void doc2pdf(String inPath, String outPath) {// 驗證license,否則轉化的pdf會帶水印if (!getLicense()) {return;}FileOutputStream os =null;try {long old = System.currentTimeMillis();File file = new File(outPath); // 新建一個空白pdf文檔os = new FileOutputStream(file);Document doc = new Document(inPath); // 加載被轉化的worddoc.acceptAllRevisions();doc.save(os, SaveFormat.PDF);long now = System.currentTimeMillis();logger.info("共耗時:" + ((now - old) / 1000.0) + "秒");// 耗時} catch (Exception e) {logger.error(null, e);} finally {try {if(os != null){os.close();}} catch (IOException e) {logger.error(null, e);}}}/*** 對應pdf文件不存在則生成pdf,不強制覆蓋* @param inPath* @param outPath*/public static void doc2pdfWhenNotExist(String inPath, String outPath){File file = new File(outPath);if(!file.exists()){doc2pdf(inPath,outPath);}}/*** 往書簽中插入圖片*/public static Map<String, String> insertImageToBookmark(String filePath, Map<String, String> keyvalues) {Map<String, String> resultMap = new HashMap<String, String>();resultMap.put("success", "false");// 驗證license,否則word會帶水印if (!getLicense()) {// 證書授權超時,請聯系管理員resultMap.put("msg", "操作失敗,證書授權超時,請聯系管理員");return resultMap;}String bookmark = "";String value = "";Iterator it = keyvalues.entrySet().iterator();try {Document doc = new Document(filePath);DocumentBuilder builder = new DocumentBuilder(doc);//獲得文檔的頁數int page = doc.getPageCount();if (page % 2 != 0) {// 文檔頁數錯誤resultMap.put("msg", "操作失敗,文檔末頁不是偶數頁,條形二維碼會與頁碼重疊,請調整正文");return resultMap;}for (int i = 0; i < keyvalues.size(); i++) {Map.Entry entry = (Map.Entry) it.next();bookmark = (String) entry.getKey();value = String.valueOf(entry.getValue());if (builder.moveToBookmark(bookmark)) {builder.insertImage(new FileInputStream(new File(value))); //插入圖片doc.save(filePath);resultMap.put("msg", "操作成功,請在編輯正文中查看");} else {// 沒有找到書簽位置resultMap.put("msg", "操作失敗,沒有找到書簽位置,請確認是否已套紅");return resultMap;}}} catch (Exception e) {// 文檔資源被占用resultMap.put("msg", "操作失敗,文檔資源被占用");return resultMap;}resultMap.put("success", "true");return resultMap;} }總結
- 上一篇: fscanf()php,fscanf函数
- 下一篇: Python 内置模块之 os