当前位置:网站首页>Use itextpdf to intercept the page to page of PDF document and divide it into pieces

Use itextpdf to intercept the page to page of PDF document and divide it into pieces

2022-04-23 16:31:48 Yangge landing

itextpdf Implement interception pdf From page to page of the document

cause :pdf Document too large ,100M above , The front end cannot be displayed at all . Solution , Back end pdf Document slicing operation , For example, ten pages are sent to the front end .

1. Use itextpdf
Import dependence

<dependency>
      <groupId>com.itextpdf</groupId>
      <artifactId>itextpdf</artifactId>
      <version>5.5.13</version>
</dependency>

2. Business logic

 @GetMapping("/download")
 public void pdf(@RequestParam(value = "page", required = false) String page, HttpServletResponse response) throws IOException, DocumentException {
    
	// File path 
	path = "C:\\Users\\pdf file .pdf"";
	//  Read pdf file 
	PdfReader reader = new PdfReader(path);
	// Total number of pages 
	int numberOfPages = reader.getNumberOfPages();
	//  Intercept the start page 
	int start = Integer.parseInt(page.substring(0, 1));
	
	// Intercept pdf Partial page , Format "2-5"  The first 2 To the first page 5 page   Page number out of range (10 page , You choose "15-20") Can only read the last page 
	//  Parameter is String type , Allow the front end to transmit value , Control which page to read 
	// reader.selectPages("2-5"); 
	reader.selectPages(page);
	
	// I don't understand the source code very much , But you need to store the file stream in memory , So use the HttpServletResponse
	PdfStamper stamp = new PdfStamper(reader, response.getOutputStream());
	
	//  Start page   If it is greater than pdf Total number of pages , Do not return file stream ,stamp.close() The result returned to 1
	if(start <= numberOfPages){
    
	     stamp.close();
	}
	reader.close();
}

3. result
More than a thousand pages of documents , I choose to intercept 1-5 page , Then it will only show 1,2,3,4,5 These pages
 Insert picture description here  Insert picture description here

版权声明
本文为[Yangge landing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231402542936.html

随机推荐