下面是三種解決方案,我發現,如果它能夠幫助別人(使用iTextSharp,Amyuni或Tracker-Software,如@Hetote在評論中說,他一直在尋找另一個庫):
使用iTextSharp的
由於answered by @martinbuberl in another question:
public static void CropDocument(string file, string oldchar, string repChar)
{
int pageNumber = 1;
PdfReader reader = new PdfReader(file);
iTextSharp.text.Rectangle size = new iTextSharp.text.Rectangle(
Globals.fX,
Globals.fY,
Globals.fWidth,
Globals.fHeight);
Document document = new Document(size);
PdfWriter writer = PdfWriter.GetInstance(document,
new FileStream(file.Replace(oldchar, repChar),
FileMode.Create, FileAccess.Write));
document.Open();
PdfContentByte cb = writer.DirectContent;
document.NewPage();
PdfImportedPage page = writer.GetImportedPage(reader,
pageNumber);
cb.AddTemplate(page, 0, 0);
document.Close();
}
在his question另一個答案由@rafixwpt,但它不會刪除的不可見元素,它清潔頁面的區域,這會影響該頁面的其它部分:
static void textsharpie()
{
string file = "C:\\testpdf.pdf";
string oldchar = "testpdf.pdf";
string repChar = "test.pdf";
PdfReader reader = new PdfReader(file);
PdfStamper stamper = new PdfStamper(reader, new FileStream(file.Replace(oldchar, repChar), FileMode.Create, FileAccess.Write));
List<PdfCleanUpLocation> cleanUpLocations = new List<PdfCleanUpLocation>();
cleanUpLocations.Add(new PdfCleanUpLocation(1, new iTextSharp.text.Rectangle(0f, 0f, 600f, 115f), iTextSharp.text.BaseColor.WHITE));
PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);
cleaner.CleanUp();
stamper.Close();
reader.Close();
}
使用Amyuni
作爲answered by @yms in another question:
IacDocument.GetObjectsInRectangle方法
GetObjectsInRectangle方法獲取指定的 中的所有對象ctangle。
然後你可以遍歷頁面中的所有對象,並刪除那些你不感興趣的:
//open a pdf document
document.Open(testfile, "");
IacPage page1 = document.GetPage(1);
Amyuni.PDFCreator.IacAttribute attribute = page1.AttributeByName("Objects");
// listObj is an array list of graphic objects
System.Collections.ArrayList listobj = (System.Collections.ArrayList) attribute.Value.Cast<IacObject>();;
// listObjToKeep is an array list of graphic objects inside a rectangle
var listObjToKeep = document.GetObjectsInRectangle(0f, 0f, 600f, 115f, IacGetRectObjectsConstants.acGetRectObjectsIntersecting).Cast<IacObject>();
foreach (IacObject pdfObj in listObj.Except(listObjToKeep))
{
// if pdfObj is not in visible inside the rectangle then call pdfObj.Delete();
pdfObj.Delete(false);
}
正如在評論@yms表示,採用新方法IacDocument.Redact在另一種解決方案版本5.0也可用於刪除指定矩形中的所有對象,並在其位置處繪製純色矩形。
使用跟蹤,軟件編輯SDK
我沒有嘗試,但它似乎是可能的,看到這個post。
由於iText提供了一個低級別的API,它允許您操作文檔中的幾乎所有內容,**這可能是**。不過**並不是說它很容易**,因爲您必須自己編寫代碼來爲頁面內容中的每個元素標識它是否可見,並且您將不得不您也可以將內容的其餘部分粘貼在一起。但是,如果您重新使用導入的頁面模板(如果要使其中的多個部分可見),則可以減少當前解決方案中生成的文檔大小。有趣的工作很多周... – mkl 2013-03-06 11:24:41
嘗試使用'PdfStamper'類進行裁剪:http://itextpdf.com/examples/iia.php?id = 231 – 2013-03-31 21:33:36
對於iTextSharp,我不是100%但是iPdfSharp能夠從表單渲染。這個想法是,你打開你的頁面,你正在裁剪,在一個表格內,然後只將你需要的部分渲染成一個新的文檔。您將不會製作多個副本,並且渲染(裁剪)的部分將成爲圖像。嘗試查看這是否是IText api下的選項。 – Alex 2013-05-28 08:31:03