2011-08-31 6 views
1
나는 현재 PDFBox를 사용 a.pdf 내에서 읽고 있습니다

를 사용하여 PDF 문서에 줄을 추가합니다. 그런 다음 각 파일의 페이지 수를 확인합니다. 이제 바닥 글 아래의 파일 끝으로 이동하여 파일이 끝났음을 알게 될 것이므로 페이지를 스테이플 링하도록 프린터에서 인식 할 수있는 이미지를 추가하려고합니다.내가 폴더 1</p> <p>내가 먼저 폴더에있는 모든 PDF 파일 목록에서 발견되는 자바

파일 목록 및 페이지 수를 가져올 때까지 도착했습니다.

마지막 페이지 끝으로 이동하여 쓰기 위해 사용하는 명령은 무엇입니까?

는 내가 텍스트로 .pdf 파일을 변환해야하거나 내가이 내가 현재 AAA 문자열로 insterted 될 경우 내가 시험 볼 것을 시도하고 사용하고있는 코드입니다 PDPageContentStream

을 사용할 수 있어야 내 pdf 파일의 마지막 페이지 프로젝트는 오류없이 실행되지만 어떤 이유로 pdf에 삽입되지 않습니다. 관심


에 대한

package pdfviewer; 

import java.io.*; 
import java.util.*; 
import java.util.List; 
import java.io.IOException; 

import org.apache.pdfbox.PDFReader; 
import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; 
import org.apache.pdfbox.pdmodel.PDPage; 
import org.apache.pdfbox.pdmodel.common.PDRectangle; 
import org.apache.pdfbox.pdmodel.font.PDFont; 
import org.apache.pdfbox.pdmodel.font.PDType1Font; 





public class Main { 

    /** 
    * @param args the command line arguments 
    */ 

     public static List flist() 
     { 
     List listfile = new ArrayList(); 
     String path = "C:/1"; 
     String files; 
     File folder = new File(path); 
     File[] listOfFiles = folder.listFiles(); 

     for (int i = 0; i < listOfFiles.length; i++) 
     { 
      if (listOfFiles[i].isFile()) 
      { 
       files = listOfFiles[i].getName(); 
       if (files.endsWith(".pdf") || files.endsWith(".PDF")) 
       { 
        listfile.add(listOfFiles[i]); 


       } 
      } 
     } 
     System.out.println(listfile); 
     return listfile; 

    } 

public static void CheckPages(List a) 
    { 
     String dir = null; 

     Object[] arraydir = a.toArray(new Object[0]); 

     for (int i=0; i< arraydir.length; i++) 
     { 
      int pages = 0; 
      PDFont font = PDType1Font.HELVETICA_BOLD; 
      float fontSize = 12.0f; 
      dir = arraydir[i].toString(); 
      System.out.println(dir); 

      try { 

        PDDocument pdoc = PDDocument.load(dir); 
        List allPages = pdoc.getDocumentCatalog().getAllPages(); 

        pages = pdoc.getNumberOfPages(); 
        System.out.println(allPages); 
        int f = pages; 
        System.out.println(pages); 

        PDPage page = (PDPage) allPages.get(i); 
        //System.out.println(page); 
        PDRectangle pageSize = page.findMediaBox(); 
        float stringWidth = font.getStringWidth("AAA"); 
        float centeredPosition = (pageSize.getWidth() - (stringWidth*fontSize)/1000f)/2f; 

        PDPageContentStream contentStream = new PDPageContentStream(pdoc,page,true,true); 
        //System.out.println(contentStream); 

        contentStream.beginText(); 
        contentStream.setFont(font, fontSize); 
        contentStream.moveTextPositionByAmount(centeredPosition, 30); 
        contentStream.drawString("AAA"); 
        contentStream.endText(); 
        contentStream.close(); 


        pdoc.close(); 

        } 
      catch (Exception e) 
        { 
         System.err.println("An exception occured in parsing the PDF Document."+ e.getMessage()); 
        } 
     } 

} 
    public static void main(String[] args) 
    { 
     List l = new ArrayList(); 
     l = pdfviewer.Main.flist(); 
     pdfviewer.Main.CheckPages(l); 


    } 

} 

덕분에 제가 위에서 사용 된 코드는 올바른 것입니다. 문제는 생성되는 PDF 파일이 버전 1.2이므로 PDF 문서 편집을 허용하지 않는 이유입니다.

버전 1.2를 사용하고 있다면 누구나해야 할 일을 알고 있습니다. 실제로 업그레이드 할 수 없기 때문에.

+0

조금만 백업 해주세요. 각 인쇄 작업의 끝에 프린터가 스테이플하지 않습니까? – Wivani

+0

그 안에 다른 프로세스를 시작하기 위해 필수 요소는 아닙니다. 파일 끝에 텍스트 줄을 삽입해야합니다. – CRL88

답변

1

라이브러리와 함께 제공되는 예제를 볼 수 있습니다. 당신에게 관심있는 두 개의 파일이 있습니다 :

1 AddImageToPDF.java AddImageToPDF.java on google code search

2 AddMessageToEachPage.java AddMessageToEachPage.java on google code search 두 번째는 모든 페이지에 메시지를 추가하지만 당신은 그것을 수정할 수 있습니다

마지막 페이지에서만 작업 할 수 있습니다. PDFBox 사용자 안내서에 따르면 src/main/java/org/apache/pdfbox/examples에 있습니다. 파일을 찾는 데 문제가있을 경우를 대비하여 Google 코드 검색에 링크를 추가했습니다.

도서관에서 작업하지 않았거나 예제를 사용하지 않았으므로 추가 된 라인/이미지의 위치에 맞게 코드를 약간 수정해야합니다. 어쨌든 이것이 도움이되고 작동하는 솔루션을 얻는다면, 솔루션을 추가하여 다른 사람들이 혜택을 누릴 수 있도록 할 수 있습니다.

편집 : 질문 작성자가 게시 한 코드를 본 후 수정되도록 추가합니다. 나는 또한 명료하게하기 위해 약간의 변경을했다.

import java.io.File; 
import java.io.FileFilter; 
import java.util.List; 
import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; 
import org.apache.pdfbox.pdmodel.PDPage; 
import org.apache.pdfbox.pdmodel.common.PDRectangle; 
import org.apache.pdfbox.pdmodel.font.PDFont; 
import org.apache.pdfbox.pdmodel.font.PDType1Font; 

public class Main { 

    /** 
    * @param args the command line arguments 
    */ 
    public static final FileFilter pdfFileFilter = new FileFilter() { 

     public boolean accept(File file) { 
      return file.isFile() && file.getName().toLowerCase().endsWith(".pdf"); 
     } 
    }; 

    public static void closeQuietly(PDDocument doc) { 
     if (doc != null) { 
      try { 
       doc.close(); 
      } catch (Exception exception) { 
       //do something here if you wish like logging 
      } 
     } 
    } 

    public static void CheckPages(File[] sourcePdfFiles,String textToInsert, String prefix) { 

     for (File sourcePdfFile : sourcePdfFiles) { 
      PDFont font = PDType1Font.HELVETICA_BOLD; 
      float fontSize = 12.0f; 
      PDDocument pdoc = null; 
      try { 

       pdoc = PDDocument.load(sourcePdfFile); 
       List allPages = pdoc.getDocumentCatalog().getAllPages(); 
       PDPage lastPage = (PDPage) allPages.get(allPages.size() - 1); 
       PDRectangle pageSize = lastPage.findMediaBox(); 
       float stringWidth = font.getStringWidth(textToInsert); 
       float centeredPosition = (pageSize.getWidth() - (stringWidth * fontSize)/1000f)/2f; 

       PDPageContentStream contentStream = new PDPageContentStream(pdoc, lastPage, true, true); 

       contentStream.beginText(); 
       contentStream.setFont(font, fontSize); 
       contentStream.moveTextPositionByAmount(centeredPosition, 30); 
       contentStream.drawString(textToInsert); 
       contentStream.endText(); 
       contentStream.close(); 

       File resultFile = new File(sourcePdfFile.getParentFile(), prefix + sourcePdfFile.getName()); 
       pdoc.save(resultFile.getAbsolutePath()); 


      } catch (Exception e) { 
       System.err.println("An exception occured in parsing the PDF Document." + e.getMessage()); 
      } finally { 
       closeQuietly(pdoc); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     File pdfFilesFolder = new File("C:\\1"); 
     File[] pdfFiles = pdfFilesFolder.listFiles(pdfFileFilter); 
     //when a file is processed, the result will be saved in a new file having the location of the source file 
     //and the same name of source file prefixed with this 
     String modifiedFilePrefix = "modified-"; 
     CheckPages(pdfFiles,"AAA", modifiedFilePrefix); 
    } 
} 
+0

안녕하세요, 나는 원래 메시지에 코드를 추가했으나 현재 오류가 발생하지 않고 컴파일 중입니다.하지만 PDF 파일에 AAA를 추가하지 않으면 메시지 삽입에 문제가 있습니다. – CRL88

+0

또한 기존 파일을 덮어 쓰려면 contentStream.sava (dir)을 추가했습니다. – CRL88

+0

contentStream이 아닌 doc에서 저장이 누락되었습니다. pdoc.close()로 문서를 닫기 전에 pdoc.save (outfile)로 저장하십시오. –