2013-04-30 63 views
6

我在紙張大小的頁面方向上有問題。
我有一個pdf文件,其中包含肖像風景頁面。使用iTextSharp設置圖像位置

此代碼完美工作。

string FileLocation = "c:\\Temp\\SomeFile.pdf"; 
    string WatermarkLocation = "c:\\Temp\\watermark.gif"; 

    Document document = new Document(); 
    PdfReader pdfReader = new PdfReader(FileLocation); 
    PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf","[temp][file].pdf"), FileMode.Create)); 

    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation); 
    img.SetAbsolutePosition(250,300); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page) 

    PdfContentByte waterMark; 
    for (int page = 1; page <= pdfReader.NumberOfPages; page++) 
    { 
     waterMark = stamp.GetUnderContent(page); 
     waterMark.AddImage(img); 
    } 
    stamp.FormFlattening = true; 
    stamp.Close(); 

    // now delete the original file and rename the temp file to the original file 
    File.Delete(FileLocation); 
    File.Move(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileLocation); 

因爲我使用絕對值設置圖像位置。

img.SetAbsolutePosition(250,300); 

如果頁面是橫向或縱向,T如何設置圖像位置?
注意:一個PDF與橫向和縱向頁面方向。

是否有機會可以使用if語句?

if (//paper is landscape) 
{ 
//code here 
} 
else 
{ 
//code here 

}

回答

1

你想要什麼來實現呢?

通常,iText會考慮頁面旋轉的值。這意味着當頁面旋轉時,座標也會旋轉。

如果你想否決此,您可以加入這一行:

stamper.RotateContents = false; 

這在Chapter 6 of my book解釋。你可以嘗試this example看出區別:

  1. 沒有旋轉,文本添加正常:hello1.pdf
  2. 旋轉,文本通常添加(=旋轉):hello2.pdf
  3. 旋轉,文本添加旋轉忽略:hello3.pdf

當然,這裏假定爲頁面定義了一個旋轉。有時,通過定義不同的頁面大小而不是定義旋轉來模擬景觀。

在這種情況下,您還應該閱讀Chapter 6,因爲它解釋瞭如何獲取文檔的MediaBox。請參閱示例PageInformation,該示例介紹了諸如GetPageSize(),GetRotation()GetPageSizeWithRotation()等方法。

這是所有記錄,但如果它不回答你的問題,請澄清。如示例中所示,添加新內容時默認會考慮輪換,所以也許我誤解了這個問題。