sách gpt4 ăn đã đi

Bài toán gói chuỗi theo chiều rộng (pixel) trong Java

In lại Tác giả: qq735679552 Thời gian cập nhật: 27-09-2022 22:32:09 34 4
mua khóa gpt4 giày nike

CFSDN nhấn mạnh vào giá trị tạo ra nguồn mở và chúng tôi cam kết xây dựng nền tảng chia sẻ tài nguyên để mọi nhân viên CNTT có thể tìm thấy thế giới tuyệt vời của bạn tại đây.

Bài viết trên blog CFSDN này về vấn đề gói chuỗi theo chiều rộng (pixel) trong Java được tác giả sưu tầm và biên soạn. Nếu các bạn quan tâm đến bài viết này thì nhớ like nhé.

Chuỗi Java bao bọc theo chiều rộng (pixel)

Trong một số trường hợp, chúng ta thường thực hiện ngắt dòng bằng cách đánh giá độ dài của một chuỗi, chẳng hạn như số ký tự. Tuy nhiên, các chuỗi tiếng Trung, tiếng Anh và kỹ thuật số có cùng độ dài thực tế lại có độ rộng khác nhau khi hiển thị. pixel) theo nghĩa phổ biến của chúng tôi.

Bao bọc dựa trên chiều rộng pixel

nhu cầu:

Bài toán gói chuỗi theo chiều rộng (pixel) trong Java

/** * 10. Tạo hình ảnh của riêng bạn và bao bọc chúng theo chiều rộng văn bản */ @Test public void creatMyImage(){ //Tổng hợp hình ảnh tổng thể thành BufferedImage bufferedImage = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB); //Đặt hình ảnh Màu nềnGraphics2D main = bufferedImage.createGraphics(); 0, 500, 500); Chuỗi văn bản = "111122223 Vì vậy, nó thân thiện với môi trường hơn khăn giấy truyền thống 3334441 Nó thân thiện với môi trường hơn khăn giấy truyền thống 11111111111111122223 Vì vậy, nó thân thiện với môi trường hơn khăn giấy truyền thống 3334441 Nó thân thiện với môi trường hơn khăn giấy truyền thống 11111111111 111122223 Vì vậy, nó thân thiện với môi trường hơn khăn giấy truyền thống 3334441 Nó thân thiện với môi trường hơn khăn giấy truyền thống 11111111111111122223 Vì vậy, nó thân thiện với môi trường hơn khăn giấy truyền thống 3334441 Nó thân thiện với môi trường hơn khăn giấy truyền thống 11111111111"; Graphics2D textG = bufferedImage.createGraphics(); textG.setColor(new Color(37,37,37)); Phông chữ hualaoContentFont = new Font("PingFang SC", Font.PLAIN, 20); .setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); drawString(textG,text,30,100,4,10,50,true,false); //Được lưu trữ vào Chuỗi cục bộ saveFilePath = "/Users/healerjean/Desktop/new.png"; ); } /** * * @param g * @param text text* @param lineHeight chiều cao dòng (chú ý đến việc kiểm soát kích thước phông chữ) * @param maxWidth chiều rộng dòng* @param maxLine số dòng tối đa* @param lề trái//lề trái của toàn bộ văn bản* @param top Lề trên // Điều chỉnh lề trên của văn bản * @param Trim Có nên cắt văn bản hay không (1. Xóa khoảng trắng ở đầu và cuối, 2. Thay thế nhiều dấu ngắt dòng bằng một) * @param lineIndent Dòng đầu tiên có được thụt lề*/ public static void drawString(Graphics2D g, String text, float lineHeight, float maxWidth, int maxLine, float left, float top, boolean Trim, boolean lineIndent) { if (text == null || text .length() == 0) return; if(trim) { text = text.replaceAll("\\n+", "\n").trim() } if(lineIndent) { text = " " + text.replaceAll("\\n", "\n "); } drawString(g, text, lineHeight, maxWidth, maxLine, left, top); @param g * @param văn bản văn bản* @param lineHeight chiều cao dòng* @param maxWidth chiều rộng dòng* @param maxLine số dòng tối đa* @param lề trái* @param lề trên cùng*/ riêng tư static void drawString(Graphics2D g, String text, float lineHeight, float maxWidth, int maxLine, float left, float top) { if (text == null || text.length() == 0 ) trả về; FontMetrics fm = g.getFontMetrics(); StringBuilder sb = new StringBuilder(); text.length(); i++) { char c = text.charAt(i); sb.append(c); int stringWidth = fm.stringWidth(sb.toString()); | stringWidth > maxWidth) { if(c == '\n') { i += 1; } if (maxLine > 1) { g.drawString(text.substring(0, i), left, top); drawString(g, text.substring(i), lineHeight, maxWidth, maxLine - 1, left, top + lineHeight } else { g.drawString); (text.substring(0, i - 1) + "...", left, top); } return; } } g.drawString(text, left, top });

  。

Gói chuỗi Java và hợp nhất Pdf dựa trên chiều rộng (pixel)

Trong quá trình phát triển thực tế, chúng ta thường nhận ra ngắt dòng bằng cách đánh giá độ dài của chuỗi, chẳng hạn như số. Tuy nhiên, khi tiếng Trung, tiếng Anh và số được hiển thị, các chuỗi có cùng độ dài thực sự có độ rộng khác nhau. nghĩa phổ biến (pixel).

Phần sau đây được giải thích cùng với hoạt động kinh doanh in lớp phủ jasper.

1. Mở đầu cho phiên bản cuối cùng của công cụ

gói chính; nhập java.awt.Color;nhập java.awt.Font;nhập java.awt.FontMetrics;nhập java.awt.Graphics2D;nhập java.awt.RenderingHints;nhập java.awt.image.BufferedImage;nhập java. io.ByteArrayInputStream;nhập java.io.ByteArrayOutputStream;nhập java.io.FileOutputStream;nhập java.io.InputStream;nhập java.io.OutputStream; nhập javax.imageio.ImageIO;nhập javax.imageio.stream.ImageOutputStream lớp công khai SubstringStr { /** * 1. Tạo ảnh của riêng bạn , Ngắt dòng theo chiều rộng văn bản*/ public void creatMyImage(String text) { // Tổng hợp hình ảnh tổng thể BufferedImage bufferedImage = new BufferedImage(595, 842, BufferedImage.TYPE_INT_RGB); //Đặt màu nền của hình ảnh Graphics2D main = bufferedImage.createGraphics(); main.fillRect(0, 0, 1500, 2600); ; Graphics2d .setColor(Màu mới(37, 37, 37); text, 30, 500, 28, 71, 20, false, false, 0); // Lưu vào chuỗi cục bộ saveFilePath = "D:\\new.png"; saveImageToLocalDir(bufferedImage, saveFilePath } Private void saveImageToLocalDir(BufferedImage); img, Chuỗi saveFilePath) { thử { //bufferedimage Chuyển đổi sang luồng đầu vào ByteArrayOutputStream bs = new ByteArrayOutputStream(); ImageOutputStream imOut = ImageIO.createImageOutputStream(bs); ImageIO.write(img, "jpg", imOut); imOut.length(); FileOutputStream(saveFilePath); //Byte luồng đầu ra[] byte = byte mới[1024]; số lượng dài = 0; while(count < length){ int len ​​​​= inputStream.read(byte, 0, 1024); =len ; outStream.write(byte, 0, len); } outStream.flush(); outStream.close(); e) { e.printStackTrace(); } } /** * @param Graphics2d * @param text text* @param lineHeight chiều cao dòng (chú ý đến kiểm soát kích thước phông chữ) * @param maxWidth chiều rộng dòng* @param maxLine số lượng tối đa dòng * @param lề trái bên trái//lề trái của toàn bộ văn bản* @param lề trên cùng//lề trên của toàn bộ văn bản* @param cắt Có cắt bớt văn bản hay không (1. Xóa khoảng trắng ở đầu và cuối, 2. Thay thế nhiều dấu ngắt dòng bằng một) * @param lineIndent Dòng đầu tiên có được thụt lề hay không*/ public static void drawString1(Graphics2D Graphics2d, String text, float lineHeight, float maxWidth, int maxLine, float left, float top, boolean crop, boolean lineIndent, int resultLine) { if (text == null || text.length() == 0) return; if (trim) { text = text.replaceAll("\\n+", "\n").trim(); . . . "); } if (lineIndent) { text = " " + text.replaceAll("\\n", "\n "); System.err.println("đã thực thi ====="); } drawString2( Graphics2d , văn bản, lineHeight, maxWidth, maxLine, left, top, resultLine); } /** * * @param Graphics2d * @param text text* @param lineHeight Chiều cao dòng* @param maxWidth chiều rộng dòng* @param maxLine số lượng dòng tối đa* @param lề trái bên trái* @param lề trên cùng*/ Private static void drawString2(Graphics2D Graphics2d, String text, float lineHeight, float maxWidth,int maxLine, float left, float top, int resultLine) { if (text == null || text.length() == 0) { return; } FontMetrics fm = graphics2d.getFontMetrics(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char strChar = text.charAt(i); sb.append(strChar); int stringWidth = fm.stringWidth(sb.toString()); if (strChar == '\n' || stringWidth > maxWidth) { if (strChar == '\n') { i += 1; System.out.println("\nĐộ dài chuỗi ký tự được tạo:" + text.substring(0, i)); } if (maxLine > 1) { resultLine = resultLine + 1; System.err.println("\nif中字符串内容为:" + text.substring(0, i)); Graphics2d.drawString(text.substring(0, i), left, top); drawString2(graphics2d, text.substring(i), lineHeight, maxWidth, maxLine - 1, left, top + lineHeight, resultLine); } else { System.err.println("\nelse中字符串内容为:" + text.substring(0, i)); Graphics2d.drawString(text.substring(0, i - 1) + "...", left, top); } trở lại; } } System.err.println("最后字符串内容为:" + text + "===行数为:" + resultLine); Graphics2d.drawString(văn bản, bên trái, trên cùng); } public static void main(String[] args) { Chuỗi văn bản = "111122223 1111111111122223所以比传统纸巾更环保3334441比传统纸巾" + System.getProperty("line.separator") + "更环66666666"+ System.getProperty("line.separator") + "所以比传统纸巾更环保3334441比传统纸巾更环。。。。。。。" + "111111122223所以比传统纸巾更环保3334441比传统纸巾更环11111111111"; Kiểm tra SubstringStr = SubstringStr mới(); test.creatMyImage(text); System.out.println("输入图片完成:D:/new.png"); } }dấu phân cách") + "Vậy thân thiện với môi trường hơn khăn giấy truyền thống 3334441 Thân thiện với môi trường hơn khăn giấy truyền thống. . . . . . . " + "111111122223 Vì vậy nó thân thiện với môi trường hơn khăn giấy truyền thống 3334441 Thân thiện với môi trường hơn khăn giấy truyền thống 11111111111"; SubstringStr test = new SubstringStr(); test.creatMyImage(text); System.out.println("Hình ảnh đầu vào đã hoàn thành : D:/mới.png"); } }dấu phân cách") + "Vậy thân thiện với môi trường hơn khăn giấy truyền thống 3334441 Thân thiện với môi trường hơn khăn giấy truyền thống. . . . . . . " + "111111122223 Vì vậy nó thân thiện với môi trường hơn khăn giấy truyền thống 3334441 Thân thiện với môi trường hơn khăn giấy truyền thống 11111111111"; SubstringStr test = new SubstringStr(); test.creatMyImage(text); System.out.println("Hình ảnh đầu vào đã hoàn thành : D:/mới.png"); } }

2. Phiên bản cuối cùng của công cụ

gói com.sinosoft.emr.util; nhập java.awt.Color; nhập java.awt.Font; nhập java.awt.FontMetrics; nhập java.awt.Graphics2D; nhập java.awt.RenderingHints; nhập java.awt.image.BufferedImage; nhập java.util.LinkedHashMap; nhập java.util.Map; nhập java.util.regex.Matcher; nhập java.util.regex.Pattern; lớp công khai SubstrUtil { private static int index = 0; /** * 1、自己做图片 ,根据文本宽度进行换行 */ public static Map creatMyImage(Chuỗi văn bản, Phông chữ, int chỉ địnhRow, Bản đồ bản đồ, int row) { index = 0; // 整体图合成 BufferedImage bufferedImage = new BufferedImage(595, 842, BufferedImage.TYPE_INT_RGB); Graphics2D Graphics2d = bufferedImage.createGraphics(); Graphics2d.setColor(Màu mới(37, 37, 37)); Graphics2d.setFont(phông chữ); graphics2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); map = myDrawString(graphics2d, text, 30, 500, allocateRow, 71, 20, map, rows); return map; } /** * 2、根据宽度截取字符串 * @param Graphics2d * @param text 文本 * @param lineHeight 行高 * @param maxWidth 行宽 * @param maxLine 最大行数 * @param left 左边距* @param top 上边距 */ Private static Map myDrawString(Graphics2D Graphics2d, String text, int lineHeight, int maxWidth, int maxLine, int left, int top, Map map, int row) { if (text == null || text.length() == 0) { return map; } FontMetrics fm = Graphics2d.getFontMetrics(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char strChar = text.charAt(i); sb.append(strChar); int stringWidth = fm.stringWidth(sb.toString()); int strLength = text.substring(0, i).length(); if (strLength >= 53 || strChar == '\n' || stringWidth >= maxWidth) { if (strChar == '\n') { i += 1;// System.out.println("Độ dài chuỗi ký tự được thêm vào:" + text.substring(0, i)); } if (maxLine > 1) { rows = rows + 1;// System.err.println("if 中字符串内容为:" + text.substring(0, i)); char value = ' ', value1 = ' '; try { value = text.substring(i).charAt(0); value1 = text.substring(i - 1).charAt(0); } catch (Exception e) { /*e.printStackTrace();*/ System.err.println("----" + e.getMessage()); } if (isChinesePunctuation(value) && checkCharCN(value1)) { map.put("row" + rows, text.substring(0, i - 1)); myDrawString(graphics2d, text.substring(i - 1), lineHeight, maxWidth, maxLine - 1, left, top + lineHeight, map, rows); } else { map.put("row" + rows, text.substring(0, i)); myDrawString(graphics2d, text.substring(i), lineHeight, maxWidth, maxLine - 1, left, top + lineHeight, map, rows); } index = index + i; map.put("index", index);// System.err.println("---không" + index); } else { rows = rows + 1; map.put("row" + rows, text.substring(0, i));// System.err.println("else không có giá trị mặc định:" + text.substring(0, i)); index = index + i; map.put("index", index); } trả về bản đồ; } } trả về bản đồ; } // 2.1 Xác định xem ký tự này có phải là boolean tĩnh công khai của Trung Quốc checkCharCN(char c) { String s = String.valueOf(c); String Regex = "[一-饥]"; Mẫu p = Pattern.compile(regex); p .matcher(s); return m.matches(); } // 2.2 Xác định xem ký tự có phải là dấu câu tiếng Trung public static boolean is ChinesePunctuation(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS || ub == Character.UnicodeBlock.VERTICAL_FORMS) { return true; } else { return false; } } /** * 3. Dành cho văn bản có chiều rộng ngắn hơn trong jasper* @author wanglong * @date 2020 November Ngày 10 tháng 1 năm 2020 7:12:14 chiều */ public static Map creatShortImage(Chuỗi văn bản, Phông chữ, int chỉ địnhRow, Bản đồ bản đồ, int row) { index = 0; // Tổng hợp hình ảnh tổng thể BufferedImage bufferedImage = new BufferedImage(595, 842, BufferedImage.TYPE_INT_RGB); Màu nền của hình ảnh Graphics2D main = bufferedImage.createGraphics(); main.fillRect(0, 0, 595, 842); Graphics2D Graphics2d = bufferedImage.createGraphics(); Graphics2d.setColor(Màu mới (37, 37, 37)); Graphics2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); bản đồ = myDrawShortString(graphics2d, text, 30, 230, chỉ địnhRow, 71, 20, bản đồ, hàng); > myDrawShortString(Graphics2D Graphics2d, String text, int lineHeight, int maxWidth, int maxLine, int left, int top, Map map, int row) { if (text == null || text.length() == 0) { return map; } FontMetrics fm = Graphics2d.getFontMetrics(); StringBuilder(); for (int i = 0; i < text.length(); i++) { char strChar = text.charAt(i); sb.append(strChar); )); if (strChar == '\n' || stringWidth > maxWidth) { if (strChar == '\n') { i += 1; //System.out.println("Nội dung chuỗi là: " + text.substring(0, i)); } if (maxLine > 1) { row = row + 1; Nội dung của chuỗi là: " + text.substring(0, i)); map.put("row" + row, text.substring(0, i)); map.put("row_len" + row, stringWidth); myDrawShortString(graphics2d, text.substring(i), lineHeight, maxWidth, maxLine - 1, left, top + lineHeight, map, row); hàng, text.substring(0, i)); map.put("row_len" + row, stringWidth); //System.err.println("Nội dung chuỗi trong else là: " + text.substring(0, i)); } return map; } } return map } public static void main(String[] args) { Map  map = new LinkedHashMap<>(); int row = 0; int onlyRow = 4; Phông chữ phông chữ = Phông chữ mới ("宋体", Font.PLAIN, 12); String text = "111122223 Vì vậy, nó thân thiện với môi trường hơn khăn giấy truyền thống 3334441 Nó thân thiện với môi trường hơn khăn giấy truyền thống 11111111111111122223 Vì vậy, nó thân thiện với môi trường hơn khăn giấy truyền thống 3334441 Dữ liệu thử nghiệm" + System.getProperty("line.dấu phân cách") + "Khi bắt chước thùng rác trên trang web chính thức của Apple, giao diện người dùng được thiết kế sử dụng phông chữ PingFang SC"+ System.getProperty("line.separator") + "Trụ sở kiểm soát và phòng ngừa thành phố Thiên Tân báo cáo rằng sau khi điều tra, Khu vực mới Binhai mới Khăn giấy Thiên Tân thân thiện với môi trường hơn 3334441 thân thiện với môi trường hơn khăn giấy truyền thống 666 nên chúng thân thiện với môi trường hơn khăn giấy truyền thống 3334441 thân thiện với môi trường hơn khăn giấy truyền thống 8888"; int length = text.length(); map = creatMyImage(văn bản, phông chữ, chỉ địnhRow, bản đồ, hàng); if (độ dài > chỉ mục) { System.out.println("Văn bản còn lại: " + text.substring(index)); .out.println("\n<<--->>>rows=" + row + ", map="+map);

Lưu ý: Người quản lý của chúng tôi đã sửa đổi lớp công cụ này và nội dung văn bản được tạo ra phù hợp với thói quen viết tiếng Trung: dấu chấm câu không được ở đầu dòng. Nếu có dấu chấm câu ở đầu dòng thì văn bản cuối cùng ở dòng trước sẽ được chuyển về dòng này.

3. Công dụng cụ thể trong dự án

3.1 lớp điều khiển

/*** 4、Chia sẻ tệp * @author wanglong* @date 2020年3月4日 下5:22:57*/@RequestMapping(value = "printEmrCourse", method = RequestMethod.GET, creates = MediaType.APPLICATION_PDF_VALUE)public void printEmrCourse(@RequestParam(value = "id", required = true) String id, @RequestParam(value = "courseType", required = true) String courseType, @RequestParam(value = "token", required = true) String token, HttpServletResponse response) { List filePathList = new ArrayList(); Map> map = iEmrCourseSelectBusi.selectEmrCourseData(id, courseType, token); thử { nếu (map.size() > 0) { đối với (int i = 0, len = map.size(); i < len; i++) { nếu (i % 2 == 0) { Chuỗi path1 = iEmrCourseSelectBusi.getCoursePdf(map.get("map" + i), "emrCourseLeft.jasper"); nếu (!"".equals(path1)) { filePathList.add(path1); } } else { Chuỗi path2 = iEmrCourseSelectBusi.getCoursePdf(map.get("map" + i), "emrCourseRight.jasper"); nếu (!"".equals(path2)) { filePathList.add(path2); } } } iEmrCourseSelectBusi.printEmrCoursePdf(filePathList, response); } } catch (Exception e) { e.printStackTrace(); }}

3.2 Lớp serviceImpl

@Service("iEmrCourseSelectBusi")lớp công khai EmrCourseBusiSelectImpl mở rộng EmrCourseSelectServiceImpl triển khai IEmrCourseSelectBusi{ riêng tư tĩnh cuối cùng dài serialVersionUID = 1L; phông chữ riêng tư = Phông chữ mới("宋体", Font.PLAIN, 12); // 读取配置文件里的jasper路径 @Value("${jasperPath}") Private String jasperPath; /** * 4、Gửi phản hồi * @author wanglong * @date 2020年11月9日下䍈3:49:23 */ @Override public Map> selectEmrCourseData(String id, String courseType, String token) { Map> resultMap = new LinkedHashMap<>(); Map map = new LinkedHashMap<>(); int rows = 0, allocateRow = 28; StringBuffer bufferStr = new StringBuffer(); String lineBreak = System.getProperty("line.separator"); // Sử dụng try { EmrCourse record = emrCourseMapper.selectByPrimaryKey(id); if (record != null) { map.put( "tên bệnh nhân", bản ghi.gettên bệnh nhân()); map.put("fkHosRegisterHosNo", record.getFkHosRegisterHosNo()); Chuỗi recordTime = DateUtil.dateToString(record.getCourseRecordTime(), "yyyy-MM-dd HH:mm"); Chuỗi doctorName = record.getDoctorRealName(); nếu ("1".equals(courseType)) { bufferStr.append(recordTime + lineBreak); Chuỗi tempStr = record.getGeneralRecords() == null ? "" : record.getGeneralRecords(); Chuỗi blankStr = ""; nếu (! "".equals(tempStr)) { blankStr = StringDealUtil.getSubString(blankStr, tempStr); } Chuỗi generalRecords = record.getGeneralRecords() == null ? "" : (blankStr + lineBreak); bufferStr.append(generalRecords); } Chuỗi updateName = record.getUpdateOprName(); Chuỗi opraterName = updateName == null ? record.getAddOprName() : updateName; bufferStr.append("\t\t\t\t\t\t\t\t\t\tTừ khóa:" + opraterName + lineBreak); String text = bufferStr.toString(); int length = text.length(); map = SubstrUtil.creatMyImage(text, font, allocateRow, map, rows); map.put("pageNum", "1"); resultMap.put("map0", map); int index = (int) map.get("index"); nếu (độ dài > chỉ mục) { Chuỗi _text = StringDealUtil.getSurplusText(văn bản, chỉ mục); resultMap = this.getOtherMap(_text, allocateRow, resultMap, 1); } } } catch (Ngoại lệ e) { e.printStackTrace(); } return resultMap; } // 4.1 Cách sử dụng khác map private Map> getOtherMap(String text, int allocateRow, Map> resultMap, int i) { int length = text .length(); Bản đồ bản đồ = new LinkedHashMap<>(); bản đồ = SubstrUtil.creatMyImage(văn bản, phông chữ, bổ nhiệmRow, bản đồ, 0); bản đồ.put("pageNum", i + 1 + " "); resultMap.put("bản đồ"+ i, bản đồ); int index = (int) map.get("chỉ mục"); nếu (chiều dài > chỉ mục) { Chuỗi _text = StringDealUtil.getSurplusText(văn bản, chỉ mục); resultMap = this.getOtherMap(_text, allocateRow, resultMap,i+1); } return resultMap; } /** * 5. Tạo pdf * @author wanglong * @date Ngày 9 tháng 11 năm 2020 1:52:42 chiều */ @Ghi đè chuỗi công khai getCoursePdf(Map map , Chuỗi jasperName) { Chuỗi fileInfo = ""; Dấu thời gian tức thì = Instant.now(); thử { JRDataSource jrDataSource = mới JRBeanCollectionDataSource(null); Tệp reportFile = new File(jasperPath + jasperName); Chuỗi importFileName = timestamp.toEpochMilli() + ".pdf"; fileInfo = jasperPath +exportFileName; //Gọi lớp công cụ JasperHelper.exportPdf2File(jasperPath + importFileName, reportFile, bản đồ, jrDataSource); Catch (Ngoại lệ e) { e.printStackTrace(); } return fileInfo; } /** * 5.1 Tổng hợp pdf để in * @author wanglong * @date 9 tháng 11 năm 2020 1:52:58 chiều */ @Ghi đè public void printEmrCoursePdf (Danh sách filePathList, phản hồi HttpServletResponse) { List files = new ArrayList(); thử { if (filePathList != null && filePathList.size() > 0) { for (int i = 0, length = filePathList.size(); i < length; i++) { String pathName = filePathList.get(i); files.add(new File(pathName)); } Chuỗi newFileName = Instant.now().toEpochMilli() + "Bản ghi lịch sử bệnh mul2one.pdf"; Chuỗi targetPath = jasperPath + newFileName; Tệp newFile = PdfMergeUtil.mulFile2One(files, targetPath); if (newFile.exists()) { // Xóa tệp pdf trước cho (Tệp tệp: tập tin) { if (file.exists() && file.isFile()) { file.delete(); newFile.getName(); PdfUtil.downloadFile(response, targetPath, newFileName); } } } bắt (Ngoại lệ e) { e.printStackTrace();inStackTrace(); } }}inStackTrace(); } }}

4. Công cụ bổ sung

package utils; import net.sf.jasperreports.engine.*;import net.sf.jasperreports.engine.util.JRLoader; import java.io.*;import java.util.Map; public class JasperHelper { /** * 1、Sửa đổi tệp pdf * @author wanglong * @date 2020年10月31日下9:10:41 */ public static void exportPdf2File(String defaultFilename, File is, Map parameters, JRDataSource conn) { try { JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn); exportPdfToFile(jasperPrint, defaultFilename); } catch (Exception e) { e.printStackTrace(); } } // 1.1 Tệp PDF private static void exportPdfToFile(JasperPrint jasperPrint, String defaultFilename) throws IOException, JRException { FileOutputStream ouputStream = new FileOutputStream(new File(defaultFilename)); JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream); ouputStream.flush(); ouputStream.close(); } }
gói utils; nhập java.io.File;nhập java.io.IOException;nhập java.util.List; nhập org.apache.pdfbox.io.MemoryUsageSetting;nhập org.apache.pdfbox.multipdf.PDFMergerUtility; @name: PdfMergeUtil* @Description: lớp công cụ ghép và hợp nhất pdf* @author wanglong* @date Ngày 25 tháng 2 năm 2020 4:33:13 chiều* @version 1.0*/public class PdfMergeUtil { /** * @Description: pdf merge splicing* @param files file list* @param targetPath merge to* @throws IOException */ public static File mulFile2One(List files,String targetPath) ném ra IOException{ // Lớp công cụ hợp nhất PDF PDFMergerUtility mergePdf = new PDFMergerUtility(); for (File f : files) { if(f.exists() && f.isFile()){ // Vòng lặp để thêm pdf cần hợp nhất mergePdf.addSource(f ); } } // Đặt tên của tệp pdf đã hợp nhất mergePdf.setDestinationFileName(targetPath); mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); trả về Tệp mới(targetPath);
package utils; import javax.servlet.http.HttpServletResponse;import java.io.*;/*** Tải PDF*/public class PdfUtil { // Tải xuống public static void downloadFile(HttpServletResponse response, String filePath, String fileName) { if (fileName != null) { response.reset(); response.setContentType("application/pdf"); // Sử dụng phương thức File file = new File(filePath); if (file.exists()) { byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } System.out.println("tải xuống thành công!"); } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } file.delete(); } } }}

Trên đây là kinh nghiệm cá nhân của mình, hi vọng có thể cho các bạn tham khảo và mong các bạn có thể ủng hộ mình.

Liên kết gốc: https://blog.csdn.net/u012954706/article/details/81511216.

Cuối cùng, bài viết về vấn đề gói chuỗi theo chiều rộng (pixel) trong Java kết thúc tại đây. Nếu bạn muốn biết thêm về vấn đề gói chuỗi theo chiều rộng (pixel) trong Java, vui lòng tìm kiếm bài viết CFSDN. duyệt các bài viết liên quan, tôi hy vọng bạn sẽ ủng hộ blog của tôi trong tương lai! .

34 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress