1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| package com.hrp.util;
import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfWriter; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder;
@Component public class PdfUtils {
public static void imageToPdf(MultipartFile file, HttpServletResponse response) throws IOException, DocumentException { File pdfFile = generatePdfFile(file); downloadPdfFile(pdfFile, response); }
private static File generatePdfFile(MultipartFile file) throws IOException, DocumentException { String fileName = file.getOriginalFilename(); String pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf"; Document doc = new Document(PageSize.A4, 20, 20, 20, 20); PdfWriter.getInstance(doc, new FileOutputStream(pdfFileName)); doc.open(); doc.newPage(); Image image = Image.getInstance(file.getBytes()); float height = image.getHeight(); float width = image.getWidth(); int percent = getPercent(height, width); image.setAlignment(Image.MIDDLE); image.scalePercent(percent); doc.add(image); doc.close(); File pdfFile = new File(pdfFileName); return pdfFile; }
private static void downloadPdfFile(File pdfFile, HttpServletResponse response) throws IOException { FileInputStream fis = new FileInputStream(pdfFile); byte[] bytes = new byte[fis.available()]; fis.read(bytes); fis.close();
response.reset(); response.setHeader("Content-Type", "application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(pdfFile.getName(), "UTF-8")); OutputStream out = response.getOutputStream(); out.write(bytes); out.flush(); out.close(); }
private static int getPercent(float height, float weight) { float percent = 0.0F; if (height > weight) { percent = PageSize.A4.getHeight() / height * 100; } else { percent = PageSize.A4.getWidth() / weight * 100; } return Math.round(percent); } }
|