2014-02-13 2 views
0

다음 요구 사항을 충족합니다.한 번에 PDF 쓰기 및 복사하는 방법?

먼저 동적으로 PDF를 만들고 싶습니다. 그러면 PDF 파일을 업로드 할 수있는 옵션이 필요합니다. 마지막으로 인쇄 버튼을 클릭하면 동적으로 생성 된 파일과 업로드 된 파일을 병합해야합니다.

인쇄 버튼을 클릭하면 한 가지 방법으로 PDF를 만들고이를 업로드 된 PDF와 결합해야합니다.

이것은 지금까지 제 코드입니다.

package com.sumit.program; 

import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.ArrayList; 
import java.util.Iterator; 
import java.util.List; 

import com.itextpdf.text.Chunk; 
import com.itextpdf.text.Document; 
import com.itextpdf.text.Element; 
import com.itextpdf.text.Font; 
import com.itextpdf.text.Image; 
import com.itextpdf.text.Paragraph; 
import com.itextpdf.text.Phrase; 
import com.itextpdf.text.pdf.BaseFont; 
import com.itextpdf.text.pdf.ColumnText; 
import com.itextpdf.text.pdf.PdfContentByte; 
import com.itextpdf.text.pdf.PdfCopy; 
import com.itextpdf.text.pdf.PdfCopy.PageStamp; 
import com.itextpdf.text.pdf.PdfImportedPage; 
import com.itextpdf.text.pdf.PdfReader; 
import com.itextpdf.text.pdf.PdfSmartCopy; 

public class CopyOfMergePdf { 

    public static void main(String[] args) { 
     try { 
      List<InputStream> pdfs = new ArrayList<InputStream>(); 
      pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Landscape.pdf")); 
      pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\client\\CoverSheet.pdf")); 
      pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\client\\ECNPRINTTEST_BP.pdf")); 
      pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Landscape.pdf")); 
      pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Document1.pdf")); 
      pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Landscape.pdf")); 
      pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Portrait.pdf")); 
      OutputStream output = new FileOutputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\merge1.pdf"); 
      CopyOfMergePdf.concatPDFs(pdfs, output, true); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void concatPDFs(List<InputStream> streamOfPDFFiles, 
      OutputStream outputStream, boolean paginate) { 

     Document document = new Document();  
     try { 
      List<InputStream> pdfs = streamOfPDFFiles; 
      List<PdfReader> readers = new ArrayList<PdfReader>(); 
      int totalPages = 0; 
      Iterator<InputStream> iteratorPDFs = pdfs.iterator(); 
      // Create Readers for the pdfs. 
      int i=1; 
      while (iteratorPDFs.hasNext()) { 
       InputStream pdf = iteratorPDFs.next(); 
       PdfReader pdfReader = new PdfReader(pdf); 
       System.out.println("Page size is "+pdfReader.getPageSize(1)); 
       readers.add(pdfReader); 
       totalPages += pdfReader.getNumberOfPages(); 
       i++; 
      } 

      int j=0; 
      System.out.println("Total pages are "+totalPages); 
      // Create a writer for the outputstream 
      PdfCopy copy = new PdfSmartCopy(document, outputStream); 
      document.open();  

      PdfImportedPage page; 
      PageStamp stamp; 
      Chunk chunk; 
      BaseFont baseFont = BaseFont.createFont("arial.ttf", BaseFont.CP1252,BaseFont.EMBEDDED); 
      Iterator<PdfReader> iteratorPDFReader = readers.iterator();    
      // Loop through the PDF files and add to the output. 
      i=0; 
      PdfContentByte under; 
      while (iteratorPDFReader.hasNext()) { 
       PdfReader pdfReader = iteratorPDFReader.next();   
       // loop over the pages in that document     
       page=copy.getImportedPage(pdfReader,pdfReader.getNumberOfPages());    
       i=i+1; 
       stamp = copy.createPageStamp(page); 
       chunk = new Chunk(String.format("Page %d",i));    
       chunk.setFont(new Font(baseFont)); 
       ColumnText.showTextAligned(stamp.getUnderContent(), 
         Element.ALIGN_CENTER, new Phrase(chunk), 
         document.getPageSize().getWidth()/2, 15, 0); 

       if(i==2){ 


       } 
       Image watermark_image = Image.getInstance("C:\\Documents and Settings\\Sumit\\Desktop\\ecn_in_pro.png"); 
       watermark_image.setAbsolutePosition(0,0);   
       under = stamp.getUnderContent();     
       under.addImage(watermark_image); 
       stamp.alterContents(); 
       copy.addPage(page); 
       copy.freeReader(pdfReader); 
       pdfReader.close();    
      } 

      outputStream.flush(); 
      document.close(); 
      outputStream.close(); 
      System.out.println("Merging of Pdfs is done......."); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if (document.isOpen()) 
       document.close(); 
      try { 
       if (outputStream != null) 
        outputStream.close(); 
      } catch (IOException ioe) { 
       ioe.printStackTrace(); 
      } 
     } 
    } 
} 

기존 PDF 파일을 모두 하나의 새 파일로 복사합니다. 동적으로 생성 된 문서를 PdfCopy 프로세스에 어떻게 추가합니까? 당신이 PdfCopy 과정에서 빈 페이지를 삽입 할 경우

+0

새 콘텐츠를 별도의 PDF (ByteArrayOutputStream을 사용하여 메모리에있을 수 있음)로 만들고 병합 할 PDF 컬렉션에 포함시키는 방법은 어떻습니까? – mkl

+0

새 Pdf 파일 만 document.newPage()를 작성하지 않고 일부 단락과 청크를 추가하면 대처하기 전에 표시해야하는 페이지가 새로 작성됩니다. –

+0

"대처"란 무엇을 의미합니까? 또한 : 나는 그 질문을 이해하지 못한다. 'PdfCopy' 프로세스에 공백 페이지를 도입하고 싶습니까? –

답변

1

, 당신은 매개 변수로 Rectangle 및 회전 (int)에 걸리는 addPage() 방법을 사용해야합니다.

PdfCopy 프로세스에 내용이있는 "직접"페이지를 삽입하려면 메모리에 문서를 만들고 해당 페이지에 내용을 추가하고 처리 할 때와 같은 방식으로 해당 페이지를 처리해야합니다 디스크에서 읽은 문서 이 같은

뭔가 : 예를 들어, 당신은 표지를 추가하려면, 경우

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
Document document = new Document(); 
PdfWriter.getInstance(document, baos); 
document.open(); 
document.add(new Paragraph("This page is empty on purpose")); 
document.close(); 
PdfReader reader = new PdfReader(boas.toByteArray()); 

, 당신은 또한 통합되고있는 모든 문서를 나열 예를 들어, 첫번째 메모리에 문서를 만들 것입니다.

+0

안녕 얘들 아, 정말 당신의 의견은 정말 고마워. –

관련 문제