0
過去一週左右,這個例外令我頭痛,我不能爲了我的生活而修復它。如果用戶選擇這樣做,我正在使用iTextSharp合併PDF文件並在其上添加水印。System.ObjectDisposedException:'無法訪問已關閉的文件。'
下面是合併代碼:
private void CreateMergedPdf(object sender, DoWorkEventArgs e)
{
using (FileStream stream = new FileStream(pdfname, FileMode.Create)) {
Document pdfDoc = new Document(PageSize.A4);
PdfCopy pdf = new PdfCopy(pdfDoc, stream);
pdfDoc.Open();
int i = 0;
foreach (File_class newpdf in AddedPDFs)
{
(sender as BackgroundWorker).ReportProgress(i++);
if (newpdf.toMerge)
{
PdfReader reader = new PdfReader(newpdf.file_path);
pdf.AddDocument(reader); //<!> Exception here
this.Dispatcher.Invoke(() => progBtxt.Text = "Merging file #" + newpdf.file_id + "..."); //Dispatcher.Invoke since UI is on seperate thread
if (add_wtrmk)//This is called for every FILE
{
AddWatermark(reader, stream);
}
}
}
}
}
而這裏的水印代碼:
private void AddWatermark(PdfReader reader, FileStream stream)
{
using (PdfStamper pdfStamper = new PdfStamper(reader, stream))//This is called for every PAGE of the file
{
for (int pgIndex = 1; pgIndex <= reader.NumberOfPages; pgIndex++)
{
Rectangle pageRectangle = reader.GetPageSizeWithRotation(pgIndex);
PdfContentByte pdfData; //Contains graphics and text content of page returned by pdfstamper
if (this.Dispatcher.Invoke(() => dropdown.Text == "Under Content"))
{
pdfData = pdfStamper.GetUnderContent(pgIndex);
}
else if (this.Dispatcher.Invoke(() => dropdown.Text == "Over Content"))
{
pdfData = pdfStamper.GetOverContent(pgIndex);
}
else//Just in case
{
MessageBox.Show("Something went wrong when adding the watermark");
return;
}
//Set font
pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40);
//Create new graphics state and assign opacity
PdfGState graphicsState = new PdfGState();
graphicsState.FillOpacity = 0.25F;
//Set graphics state to pdfcontentbyte
pdfData.SetGState(graphicsState);
//Color of watermark
pdfData.SetColorFill(BaseColor.GRAY);
pdfData.BeginText();
//Show text as per position and rotation
this.Dispatcher.Invoke(() => pdfData.ShowTextAligned(Element.ALIGN_CENTER, WtrmkTextbox.Text, pageRectangle.Width/2, pageRectangle.Height/2, 45));
pdfData.EndText();
}
}
}
對合並的代碼出現錯誤,特別是線「PDF .AddDocument(讀取器);」 但是只有當我嘗試在多個文件上添加水印時(只有一個文件完美工作),我纔會收到此錯誤。
我想無論是我已經關東西太早,或addWatermark()做 - 我試着改變我們的使用 statemets無濟於事。我一定錯過了一些東西
我的猜測是'PdfStamper'正在關閉時,你'AddWatermark'處理它的流。當你添加第一頁時,它不會失敗嗎?就在您添加了水印之後的第二次? –
是的,這是正確的 –
好吧,我建議刪除'PdfStamper'使用語句只是爲了測試理論。如果解決了這個問題,那麼只需要重構代碼,以便在整個流完成之前不調用內部配置。 –