首页 > 解决方案 > 返回已使用 java/spring 通过 iText 剪辑的 pdf

问题描述

我有这个 spring 应用程序,用户将多部分 pdf 上传到端点,我希望文件通过 iText 进行剪辑,然后返回到浏览器进行查看/下载。

@RequestMapping("/upload")
  public String upload(Model model,@RequestParam("files") MultipartFile file) throws IOException {
      StringBuilder fileNames = new StringBuilder();
      File convertFile = new File(file.getOriginalFilename());
      convertFile.createNewFile();
      FileOutputStream fos = new FileOutputStream(convertFile);
      fos.write(file.getBytes());
      fos.close();

      System.out.println(fos.toString());
      System.out.println(fos    );

      model.addAttribute("msg", "Successfully uploaded files "+fos);
      return "uploadstatusview";
  }

我没有成功尝试更改多部分文件的类型,以便 iText 可以接收它,但它不会工作。请帮助我提出一些实施想法,因为现在我很困惑。

protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));

        for (int p = 1; p <= pdfDoc.getNumberOfPages(); p++) {

            if (p == 1){
                PdfPage page = pdfDoc.getPage(p);

                Rectangle media = page.getCropBox();

                if (media == null) {
                    media = page.getMediaBox();
                }
                float llx = media.getX() + 0;
                float lly = media.getY() + 250;
                float w = media.getWidth() - 250;
                float h = media.getHeight() - 500;
                // It's important to write explicit Locale settings, because decimal separator differs in
                // different regions and in PDF only dot is respected
            String command = String.format(Locale.ENGLISH,
                    // re operator constructs a rectangle
                    // W operator - sets the clipping path
                    // n operator - starts a new path
                    // q, Q - operators save and restore the graphics state stack
                    "\nq %.2f %.2f %.2f %.2f re W n\nq\n", llx, lly, w, h);
            // The content, placed on a content stream before, will be rendered before the other content
            // and, therefore, could be understood as a background (bottom "layer")
            PdfPage pdfPage = pdfDoc.getPage(p);
            new PdfCanvas(pdfPage.newContentStreamBefore(), pdfPage.getResources(), pdfDoc)
                    .writeLiteral(command);
            // The content, placed on a content stream after, will be rendered after the other content
            // and, therefore, could be understood as a foreground (top "layer")
            new PdfCanvas(pdfPage.newContentStreamAfter(), pdfPage.getResources(), pdfDoc)
                    .writeLiteral("\nQ\nQ\n");
            }

标签: javaspringpdfitext

解决方案


推荐阅读