itextsharp,itext , iTextSharp 5.5.6 PdfCopy Failing with “Cannot access a closed file”

## Question:

Tag: itextsharp,itext

This seems to be similar to this question: Merging Tagged PDF without ruining the tags

I'm using the latest iTextSharp NuGet package (v5.5.6) trying to merge two tagged PDFs. When calling Document.Close() I'm getting an ObjectDisposedException originating from PdfCopy.FlushIndirectObjects().

at System.IO.__Error.FileNotOpen()
at System.IO.FileStream.get_Position()
at iTextSharp.text.io.RAFRandomAccessSource.Get(Int64 position, Byte[] bytes, Int32 off, Int32 len) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\io\RAFRandomAccessSource.cs:line 96
at iTextSharp.text.io.IndependentRandomAccessSource.Get(Int64 position, Byte[] bytes, Int32 off, Int32 len) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\io\IndependentRandomAccessSource.cs:line 76
at iTextSharp.text.pdf.RandomAccessFileOrArray.Read(Byte[] b, Int32 off, Int32 len) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\RandomAccessFileOrArray.cs:line 235
at iTextSharp.text.pdf.RandomAccessFileOrArray.ReadFully(Byte[] b, Int32 off, Int32 len) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\RandomAccessFileOrArray.cs:line 264
at iTextSharp.text.pdf.RandomAccessFileOrArray.ReadFully(Byte[] b) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\RandomAccessFileOrArray.cs:line 254
at iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw(PRStream stream, RandomAccessFileOrArray file) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfReader.cs:line 2406
at iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw(PRStream stream) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfReader.cs:line 2443
at iTextSharp.text.pdf.PRStream.ToPdf(PdfWriter writer, Stream os) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PRStream.cs:line 224
at iTextSharp.text.pdf.PdfIndirectObject.WriteTo(Stream os) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfIndirectObject.cs:line 157
at iTextSharp.text.pdf.PdfWriter.PdfBody.Write(PdfIndirectObject indirect, Int32 refNumber, Int32 generation) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfWriter.cs:line 389
at iTextSharp.text.pdf.PdfWriter.PdfBody.Add(PdfObject objecta, Int32 refNumber, Int32 generation, Boolean inObjStm) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfWriter.cs:line 379
at iTextSharp.text.pdf.PdfCopy.WriteObjectToBody(PdfIndirectObject objecta) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfCopy.cs:line 1238
at iTextSharp.text.pdf.PdfCopy.FlushIndirectObjects() in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfCopy.cs:line 1186
at iTextSharp.text.pdf.PdfCopy.FlushTaggedObjects() in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfCopy.cs:line 884
at iTextSharp.text.pdf.PdfDocument.Close() in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfDocument.cs:line 825


Here is the code that is producing the exception. If I don't call copy.SetTagged() and don't pass true as the third argument to GetImportedPage() the code executes without exception, but ignores all tagging.

using(var ms = new MemoryStream())
{
var doc = new Document();
var copy = new PdfSmartCopy(doc, ms);
copy.SetTagged();
doc.Open();

string[] files = new string[]{@"d:\tagged.pdf", @"d:\tagged.pdf"};
foreach(var f in files)
{
var reader = new PdfReader(f);
int pages = reader.NumberOfPages;
for(int i = 0; i < pages;)
copy.AddPage(copy.GetImportedPage(reader, ++i, true));
copy.FreeReader(reader);
reader.Close();
}

// ObjectDisposedException
doc.Close();

ms.Flush();
File.WriteAllBytes(@"d:\pdf.merged.v5.pdf", ms.ToArray());
}


Looking at the 5.5.6 source branch it looks like RAFRandomAccessSource.cs line 96 is the culprit.

public virtual int Get(long position, byte[] bytes, int off, int len) {
if (position > length)
return -1;

// Not thread safe!
if (raf.Position != position)


raf.Position has been disposed at this point, but I can't tell from where it has been disposed.

I'm hoping that I just need to do something more than simply call copy.SetTagged() and pass true to GetImportedPage() to fix the issue.

Answer:

You are closing the PdfReader instances too early. You can only trigger:

reader.Close();


after you close the PdfSmartCopy instance, hence you have to rethink where you create the different PdfReader objects (not inside the loop).

The reason why the different PdfReader instances have to remain open is purely technical: merging structured trees (where all the tagging information is stored) isn't trivial. This can only happen at the moment all the other work is done. It requires access to the original structures of the separate documents. If you close the PdfReader to such a document, that structure can no longer be retrieved.

# Related:

## Add image and text in one line itextsharp

vb.net,pdf,itextsharp
Below code is adding text and image in separate lines. How can I display them in one line? pdfDoc.Add(image) pdfDoc.Add(New Paragraph(text)) ...

## Control 'testGridview' of type 'SPGridView' must be placed inside a form tag with runat=server

c#,gridview,itext,export-to-pdf,spgridview
I have a spgridview and want to export its content to pdf. I am using itextsharp for the same. But error is encountered at rendercontrol call. I have already tried the solutions mentioned in the below thread. Question Also I have tried using public override void VerifyRenderingInServerForm(Control control) { return;...

## How to convert pdf into text file using itext liberary

itext
Below is my code for converting a pdf file into a text file. The code successfully runs, but it doesn't generate the resulting text file (Sample.txt). Can anyone shed some light on this? The code is partly based on an example of the first iText in action book... import com.lowagie.text.*;...

## Merge documents to create TOC in iText (Java)

java,pdf-generation,itext,toc
When creating documents with iText that need a table of contents, I have usually used a process where I create the main document in memory, create the TOC as a separate document in memory (using dummy links), merge them as a third document, and then use a PdfStamper to reconcile...

## I have a pdf from which I have to extract data and show but I am getting this exception, I'm not being able to figure out what is this Exception is?

java,exception,servlets,itext,pdf-reader
I have this pdf file to extract data from, but the problem is when I'm running this piece of code as a simple java program, it works like a charm but when I tried this code on JSP servlet it gave out this exception and I'm not being able to...

## Textfield data is getting too small, when we enter more data into the textbox

java,itext
If I apply, text.setOptions(TextField.MULTILINE | TextField.REQUIRED); to my text field, then I can enter more data, but the problem is the data is getting too small, then it becomes scrollable. Can we get a scrollbar instead, before it gets too small?...

## iTextPDF hyperlink not linking to the right place

java,itext,itextpdf
I have a bunch of PDF's which I have merged by this point in the code. At the beginning of the merged PDF I have a contents page which links to said PDF's respectively. These pdfAction.gotoLocalPage links sometimes don't work correctly and instead jump to between the bottom of the...

## How to write bulleted list in pdf using itext jar but item should not in next line

itext
Below is the code I have searched from net. this code is printing the each list item in next line but I don't want like that. Below is expected output I want to write in pdf: List orderedList = new List(List.ORDERED); orderedList.add(new ListItem("Item 1")); orderedList.add(new ListItem("Item 2")); orderedList.add(new ListItem("Item 3"));...

## Will iTextSharp version 5.5.2 run with C#, .net version 3.5 code?

c#,pdf,itextsharp
I need to merge mutiple pdf files into one pdf. My code is using .net and C# version 3.5. From what I have read here in StackOverflow and elsewhere, iTextSharp seems to be most highly recommended pdf file manipulation utility. Will the latest version of iTextSharp on sourceforge.net, I think...

## PDF Filter used to encode data in iTextSharp

pdf,pdf-generation,itextsharp
Currently I am working with iTextSharp library to generate PDF files and these files will be processed by some file processor. This pdf file processor is having some limitation with pdf filters which it will use to decode the data from the file. I am very keen to know which...

## Multiple signatures with Itext - issue with existing signature blocks

java,pdf,itext
So im currently working on a project to sign PDF documents and I ran into a problem. So i can sign documents correctly without any problems if I specify the block to sign i.e. signatureAppearance.setVisibleSignature(rectangle, page, signingBlockName); I can add multiple signatures without a problem and all of the signatures...

## Itext rectangle from milimeters

itext,rectangles,dimensions
I try draw a A5 rentangle in a PDF with Itext using Rectangle class and Utilities.milimetersToPoints method but when i print the PDF and measure the rectangle the measurments is not the A5 dimensions. public static boolean createPDF(String pathPDF) { Document document = new Document(PageSize.A4); try { PdfWriter writer =...

## How to change the spacing between words and characters?

java,itext
I want to set the text alignment to justified, but I don't want iText to add any extra space between the characters (see figure 1). I prefer space between words as shown in figure 2. With this code, I get the result shown in figure 1. public static void main(String[]...

## Clear MemoryStream after passing the objects to a different function

c#,smtp,itextsharp,memorystream
My main question is if I pass object to a function that are using a MemoryStream how to I go about clearing the memorystream? See my code below. In more detail: I'm trying to send multiple emails while creating PDFs on the fly using iTextSharper. I want to make sure...

## Center a table horizontally with iText's XMLWorker

itext,xmlworker
I've tried centering a table in two ways: Attempt 1 code: <h1>Attempt 1</h1> <table style="width: 50%; margin: 0 auto;"> <tr> <th>foo</th> <td>bar</td> </tr> <tr> <th>foo</th> <td>bar</td> </tr> </table> Attempt 2 code: <h1>Attempt 2</h1> <table style="width: 50%;" align="center"> <tr> <th>foo</th> <td>bar</td> </tr> <tr> <th>foo</th> <td>bar</td> </tr>...

## Converting images to PDF with iTextSharp preserve clipping path

c#,itextsharp,itext,jpeg,clipping
We're looking to convert images in bulk to PDF, programmatically. So far it looks like we will be using iTextSharp but we have an issue with JPG images with clipping path. We are using the following code in our tests: using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None)) {...

## Table border does not automatically fit into contents

c#,asp.net-mvc,itextsharp
I have an invoice being constructed via iTextSharp (4.1.2). My problem lies on a certain part of my invoice wherein I display the terms and conditions and the payment terms. The following image below shows my problem. However, when the dynamic rows are not present (I mean no selected discounts,...

## giving error while creating pdf.The process cannot access the file.because it is being used by another process

c#,asp.net,pdf,itextsharp
im exporting web page div into pdf and sending that mail to pdf. for first time its creating pdf and sending mail properly.but for next time its giving error saying . file is bieng used by a another process at this line PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(strPath, FileMode.Create)); my...

## Adding an imported PDF to a table cell in iTextSharp

pdf,itextsharp
I am creating a new PDF that will contain a compilation of other documents. These other documents can be word/excel/images/PDF's. I am hoping to add all of this content to cells in a table, which is added to the document - this gives me the goodness of automatically adding pages,...

## Geneate table in pdf using itextsharp vb.net from sql

sql,vb.net,pdf,itextsharp
I can create a simple pdf file like "Hello world", but I want to generate a table in pdf file using vb.net. I am using itextsharp library. This is what I have tried so far. Protected Sub Create_PdfTable_Click(sender As Object, e As EventArgs) Handles Create_PdfTable.Click Dim table As New PdfPTable(2)...

## Sign concatenated PDF in append mode with CERTIFIED_NO_CHANGES_ALLOWED

itext,itextpdf
I tried to sign PDF with append mode and certification level CERTIFIED_NO_CHANGES_ALLOWED but certain PDF files shown as modified and therefore invalid in Acrobat. itext 5.5.6, code: PdfStamper stp = PdfStamper.createSignature(reader, os,'\0',null,true); PdfSignatureAppearance app = stp.getSignatureAppearance(); app.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); PDf file is created with wkhtmltopdf and concatenated with itself with pdfunite (CentOS...

## How to Check PDF is Reader enabled or not using C#?

c#,pdf,itextsharp,pdfbox
My only requirement is to find a selected pdf in a folder is Reader enabled or not, more specifically if usage rights are defined in a way that allows people to add annotations (e.g. comments). I am doing this in windows application. If I click a button, an event is...

## C# ItextSharp Fontawesome Icons ( currency ) - PDF

c#,pdf,icons,itextsharp
i have problem is importing the icons (fontawesome-webfont.ttf) and showing them on PDF -but i am unable to show them on the PDF especialy currency icon (fa-money) some of the icons i was able to get it from the CultureInfo class if any thing i missed apart from this chunkRows...

## Viewing PDF with Java [duplicate]

java,pdf,itext
This question already has an answer here: Java PDF Viewer 2 answers I am working on a program that should create, Show and Extract text from PDF files but i cant find a free library that will show PDF files or at least convert them to images to work...

## error while creating PDF

android,pdf,android-studio,itext
I am trying to generate a PDF using Android Studio. I am using the iText library, but when I add it into Android studio, I get the following error: Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2 When I remove the...

## How to extract text by a selected area from a PDF file using iText?

java,swing,pdf,awt,itext
I am working on a program that extract texts from a PDF file in a specific area, I am using java and iText library. Right now, i can extract data by taping the area coordinations using this code: import java.io.IOException; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.FilteredTextRenderListener; import com.itextpdf.text.pdf.parser.LocationTextExtractionStrategy; import com.itextpdf.text.pdf.parser.PdfTextExtractor;...

## Signing PDF - memory consumption

itext,itextpdf
I tried some utilities for digital PDF signing based on iText v1 or v2 and found out that it seems whole PDF is loaded into memory (for 60M PDF process can take up to 300-400MB of memory). Can recent iText versions sign PDF without load it into memory? Updates I...

## Add Uploaded File(s) to iTextSharp PDF New Page

c#,pdf,itextsharp
I'm at the last step in completing a pdf generator. I am using iText sharp and i am able to stamp a base64 image with no problem thanks to help from StackOverflow. My question is how would I iterate over posted files and add a new page with posted image...

## iTextSharp: “The document is not open” error - when it actually is

itextsharp
I have this code: private static byte[] ConvertPdfDocument(Document document, PdfPTable headerTable, PdfPTable affidavitsTable) { byte[] b; using (MemoryStream ms = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(document, ms); if (document.IsOpen() == false) { document.Open(); } document.Add(headerTable); document.Add(affidavitsTable); document.Close(); writer.Close(); b = ms.ToArray(); } return b; } The "document" object is...

## How to reorder the pages of a PDF file?

java,pdf,itext
I am generating Table of Contents at last,I want to move Table of Contents at Beginning. Suppose that I have 16 pages in my PDF and that the TOC starts from page 13 and ends on page 15. I want to move the TOC to the second page, so that...

## Ordered and Unordered List is not rendered during the PDF Generation

pdf,pdf-generation,html-parsing,html-lists,itext
I am using iText-5.5.6 and XMLWorker-5.5.6. I am having strange issue during the PDF Generation where as I am not able to see the Ordered or Unordered list from the source HTML Content. I am getting the HTML Content from the Editor Control. And the content is like the below:...

## PDF generated by iText -> text missing after saving PDF to local drive

java,pdf,pdf-generation,itext
I am producing a PDF file in a HttpServlet with itText. Adding a Text on the canvas. If I open the url the PDF is shown correctly with the text. Also if I print it direclty from the browser, the text is visible on the printed paper. If I download...

## ITextSharp setting background working not for all fields

c#,itextsharp
I have the following string of code setting bacground for all pdf fields: using (var pdfReader = new PdfReader(template)) { using (var pdfStamper = new PdfStamper(pdfReader, new FileStream(fileName, FileMode.Create)){FormFlattening = true}) { var fields = pdfStamper.AcroFields; foreach (var field in fields.Fields) { fields.SetFieldProperty(field.Key, "bgcolor", new BaseColor(Color.Red), null); } } }...

## link coming twice while exporting to pdf using itextsharp

pdf,gridview,itext
my asp boundfield: <asp:BoundField DataField = "SiteUrl" HtmlEncode="false" HeaderText = "Team Site URL" SortExpression = "SiteUrl" ></asp:BoundField> My itextsharpcode for (int i = 0; i < dtUIExport.Rows.Count; i++) { for (int j = 0; j < dtUIExport.Columns.Count; j++) { if (j == 1) { continue; } string cellText = Server.HtmlDecode(dtUIExport.Rows[i][j].ToString());...

## Watermark in PDF file is hiding behind images

c#,pdf,itextsharp
I want to add a watermark to an existing PDF by using the following: ITextSharp insert text to an existing pdf The 3rd answer is working but if the PDF contains an image then the watermark is hidden behind it....

## Itext get special letters from pdf

java,pdf,itext
I am trying to extract accented words from pdf e book . The best results are produced when using itext library , but I fail to get accents from words . example : побеђивање -should come out as- побеђи́ва̄ње (accents are missing) The letters are Cyrillic Serbian . I tried...

## ITextSharp rotate all text on a page about a point

.net,pdf,rotation,itextsharp,affinetransform
I've just burnt an hour working out a solution to this, which I'm sure isn't the best one; I'd be happy to hear if there is a better solution. I need to rotate all text on a page about a point. I've tried transforming the point to the origin, performing...

## Can't set RTL direction for Hebrew letters while converting from *.xhtml to *.pdf by using iText library

java,itext,right-to-left,hebrew,xmlworker
I'm trying to convert *.xhtml with Hebrew characters (UTF-8) to PDF by using iText library but I getting all letter in reverse order. As far I understand from this question I can set RTL only for ColumnText and PdfCell objects: Arabic (and Hebrew) can only be rendered correctly in the...

## iText, FileNotFoundException when adding image to pdf

android,image,pdf,itext
I am trying to add an image to my pdf using iText and when following the iTexts documentation on this its just simply telling me to do this: Image img = Image.getInstance("res/drawable/toplogos.png"); document.add(img); But I am getting FileNotFoundException. Why is that? The file is in the drawable folder. Thanks....

## Why do the widths of my textboxes differ when the code is effectively identical (iTextSharp)?

c#,pdf-generation,itextsharp
I've got a PDF file that I'm generating using iTextSharp; here's a part of it that is causing me to suffer from called alopecia areata due to excessive head-scratching: Here's the code: The longer initial text box on the row (below "Tier 2 Signature..."): PdfPTable tblSection6_Row6 = new PdfPTable(5); tblSection6_Row6.WidthPercentage...

## Itext std deviation symbol σ not printing

itext,symbol
Using itext to generate PDFs and I have a symbol σ which does not print in the pdf. Is this because of font selection (using HELVETICA_BOLD)? Can anyone help

## Get exact cordinates of the page to add a watermark with different page rotation using iTextSharp

c#,.net,itextsharp
I have been trying to position a Text Water marks on PDF file using iTextSharp and i am struggling to find the coordinates on each page. it works fine when all the pages in pdf file are of same rotation but if the rotation is different then the coordinates are...

## iTextSharp 5.5.6 PdfCopy Failing with “Cannot access a closed file”

itextsharp,itext
This seems to be similar to this question: Merging Tagged PDF without ruining the tags I'm using the latest iTextSharp NuGet package (v5.5.6) trying to merge two tagged PDFs. When calling Document.Close() I'm getting an ObjectDisposedException originating from PdfCopy.FlushIndirectObjects(). at System.IO.__Error.FileNotOpen() at System.IO.FileStream.get_Position() at iTextSharp.text.io.RAFRandomAccessSource.Get(Int64 position, Byte[] bytes, Int32 off,...

## iTextPdf-How to add a FormField to Section without Position?

java,itext
In want to add interactive from fields like check boxes to a new created multiple page pdf, in the example from itext the code looks like this: PdfContentByte canvas = writer.getDirectContent(); Rectangle rect = new Rectangle(180, 806 * 40, 200, 788 * 40); RadioCheckField checkbox = new RadioCheckField(writer, rect, "box1",...

## How to flatten pdf with Itext in c#?

c#,itext
I need to remove all form fields of a pdf, so I am using iText and try to flatten the pdf. Because of legacy code I am restricted to iText version 4.1.6.1 My Code is: public static byte[] RemoveAcroFields(String filename) { if (filename != null && File.Exists(filename)) { byte[] pdfFile...

## Crop Pdf from each edge using itextshap

c#,pdf,itextsharp
I am trying to crop pdf 5 mm from every edge i.e top,bottom,right and left. I tried with below code public void TrimPdf(string sourceFilePath, string outputFilePath) { PdfReader pdfReader = new PdfReader(sourceFilePath); float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(5); using (FileStream output = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write)) using (PdfStamper pdfStamper = new PdfStamper(pdfReader,...

## How can I write all the pages in the text document

java,itext
I am trying to write extracted text of the pdf file into text document but currently, only the first page is being written in the text document although 6 pages are being output in the console of eclipse. How can I fix that? I appreciate any help. try { PdfReader...

## Error in PDF Export

java,pdf,itext
Here is my code snippet- getResponse().setContentType(NAPSConstants.PDF_CONTENT_TYPE); getResponse().setHeader(NAPSConstants.PDF_CONTENT_DISP, NAPSConstants.PDF_ATTACHMENT_FILE+getText("rcmid.details")+NAPSConstants.PDF_EXTN); //Set the Page Size Document document = new Document(PageSize.A3, 40, 40, 40, 40); PdfPTable table = new PdfPTable(rcmDetailsCols.length); for(RCMIDPartsDetailsDTO part : rcmidDTO.getPartsDetailsDTO()){ table.addCell(part.getPartStatus().equals(NAPSConstants.Active) ? PDFHelper.dataCell(...