2014-04-30 3 views
1

pdf를 사용하고 Itextsharp 및 PdfWriter를 사용하여 첫 페이지에 텍스트를 인쇄하는 프로그램이 있습니다. 현재 이것은 텍스트를 입력해야하는 각 PDF에 대해 의도 된대로 작동하고 있습니다. 그러나 소스 pdf의 레이아웃이 가로 인 경우 작성자는 pdf의 첫 번째 페이지에 텍스트를 입력 한 후 레이아웃을 세로로 회전합니다. pdf에 텍스트를 입력 한 후 기본 레이아웃이 세로로 변경된 이유에 대한 설명서를 찾을 수 없습니다. 이 회전으로 인해 원본 레이아웃이 가로형이므로 정보가 오른쪽에서 잘 리게됩니다.iTextSharp PdfWriter 회전해야 할 때의 페이지 레이아웃

나는 PdfStamper와 관련된 다른 대답을 보았지만 기존 코드를 조작하는 데 어려움을 겪고 있습니다. 임 C 프로그래밍, PDF 조작 및 iTextSharp 프로그래밍에 상당히 새로운 기능을 제공합니다. 강조 할 수있는 pdf 텍스트의 최종 목표입니다.

//Adds white invisible text to the pdf document that is highlightable 
public static void stamp(string pdfName, string filePath, string textToStamp) 
{ 
    //Make a Temporary copy of the original to manipulate 
    string tempPath = @"C:\TemporaryFilePath\" + pdfName + ""; 
    File.Copy(filePath, tempPath); 
    //Make a new reader using the copied source file 
    PdfReader reader = new PdfReader(tempPath); 
    using (Document document = new Document()) 
    { 
     using (PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create))) 
     { 
      document.Open(); 
      int numofpages = reader.NumberOfPages; 
      for (int p = 1; p <= numofpages; p++) 
      { 
       //create the ContentByte to give the text a position on the first page 
       PdfContentByte cb = writer.DirectContent; 
       //Get the page to work with 
       PdfImportedPage page = writer.GetImportedPage(reader, p); 

       document.NewPage(); 
       cb.AddTemplate(page, 0, 20); 
       var FontColour = new BaseColor(255, 255, 255); 
       var MyFont = FontFactory.GetFont("Times New Roman", 12, FontColour); 
       //Gets the first page and sends the text to the upper left corner 
       if (p == 1) 
       { 
        if (TextToStamp!= null) 
        { 
         document.Add(new Paragraph("Hello World", MyFont)); 
        } 
       } 
       document.Close(); 
      } 
     } 
     reader.Close(); 
     File.Delete(tempPath); 
    } 

추가 하시겠습니까? 감사합니다.

+1

'PdfWriter'를 사용하지 않아야합니다. 설명서를 읽었다 고 말하면 http://manning.com/lowagie2/samplechapter6.pdf를 읽었습니까? 그렇다면이 장에서 명확하지 않은 내용을 설명하여 제게 확신을 줄 수 있도록하십시오. 제 3 판을 쓸 때 올바르게 설명하십시오. (귀하의 요구 사항이 명확하지 않다는 점에 유의하십시오. 기존 텍스트를 강조하고 싶습니까? 텍스트의 좌표를 어떻게 가져 옵니까?) –

+0

요구 사항의 모호성을 유감스럽게 생각합니다. 목적은 첫 번째 페이지의 왼쪽 상단 영역에 텍스트를 추가하는 것입니다. 스탬퍼로 이해하기 힘든 부분은 특정 페이지에 추가 된 정보를 제한하는 방법이지만 나머지 페이지는 PDF로 유지하는 것입니다. 독자가 첫 번째 페이지 만 가져온 다음 다시 문서에 참여시키는 것이 좋습니다. – Ben

답변

0

브루노에 의해 게시 된 정보를 사용하여,이 솔루션을 함께했다. 이렇게하면 레이아웃이 무엇이든 관계없이 페이지에 정보를 스탬핑 할 수 있으며 적은 양의 사용자 정의가 가능합니다.

public static void AddText(string pdfName, string filePath, string textToStamp, float? x = null, float? y = null) 
{ 
    //x and y are used to position the text and allow multiple different templates to use the same method 
    //Designate the Temporary source to be used 
    string tempPath = @"C:\TemporaryFilePath\" + pdfName + ""; 
    //Copy to file to the source path 
    File.Copy(filePath, tempPath); 
    PdfReader reader = new PdfReader(tempPath); 
    iTextSharp.text.Rectangle pageSize = reader.GetPageSizeWithRotation(1); 
    //Convert the pageHeight into a float 
    int pageHeight = Convert.ToInt32(pageSize.Height); 
    PdfStamper stamper = new PdfStamper(reader, new FileStream(filePath, FileMode.Create)); 

    PdfContentByte canvas = stamper.GetOverContent(1); 
    //Set a default value if x and y have no value 
    if (x.HasValue == false) 
    { 
     x = 35; 
    } 
    if (y.HasValue == false) 
    { 
     y = 30; 
    } 
    //choose the font type 
    var FontColour = new BaseColor(255, 255, 255); 
    var MyFont = FontFactory.GetFont("Times New Roman", 10, FontColour); 
    ColumnText.ShowTextAligned 
       (canvas, Element.ALIGN_LEFT, new Phrase("Hello World", MyFont), (float)x, pageHeight - (float)y, 0); 

    stamper.Close(); 
    reader.Close(); 
    File.Delete(tempPath); 
} 
1

브루노가 지적한 http://manning.com/lowagie2/samplechapter6.pdf을 읽을 때 특정 페이지의 특정 위치에 텍스트를 추가하는 방법은 PdfStamper을 사용하는 방법을 설명하는 6.3.1에 특히주의하십시오. 또한 가로 페이지의 두 가지 유형, 즉 너비> 높이 인 회전 된 페이지와 페이지 간의 차이점을 보여줍니다.

전체 코드 예제

는 여기에서 찾을 수 있습니다 : http://www.itextpdf.com/examples/iia.php?id=117