itextsharp stamping form pdf onto other pdf - pdf

I'm using itextsharp in vb.net to stamp some backgrounds (ie other single page pdfs) onto another pdf.
So I have a 5 page 'blank' pdf, on which I stamp page 1 with the first page from a file called page1.pdf, then I put the first page of page2.pdf as a background to page 2 etc etc.
It's worked fine so far, but I've come across a problem with stamping a particular pdf onto my 'blank' - the issue appears to be with a file I'll call 'page4.pdf' and it seems likely it's because page4.pdf has been designed as a fillable form.
When I stamp page4 on and open up the blank file in Adobe reader, I get the message:
There was an error processing a page. There was a problem reading this document (18)
Could anyone suggest a way I can stamp a pdf with a form pdf as the source without this issue?
Thanks!
Here's an extract from the code I'm using for stamping (it does other stuff and involves a loop to go through the pages of the pdf, but I've just put the actual stamp bit below to keep things simple):
Dim background As PdfContentByte
Dim page As PdfImportedPage = Nothing
Dim reader As PdfReader = New PdfReader(sourcepdf)
Dim stamper As New itextsharp.text.pdf.PdfStamper(reader, New System.IO.FileStream(outputpdf, System.IO.FileMode.Create))
Dim s_reader As New PdfReader(backfile)
page = stamper.GetImportedPage(s_reader, 1)
background.AddTemplate(page, 0, 0)
stamper.Close()
reader.Close()
s_reader.Close()
Here's the code I've been trying out to convert the form pdf to a 'non-form', which I was hoping would eliminate the stamping problem (no success so far):
Dim pdfReader As PdfReader = New PdfReader(inputpdf)
Dim pdfStamper As itextsharp.text.pdf.PdfStamper = New PdfStamper(pdfReader, New FileStream(outputpdf, FileMode.Create))
pdfStamper.AnnotationFlattening = True
pdfStamper.FreeTextFlattening = True
pdfStamper.FormFlattening = True
pdfStamper.Close()

Issue was nothing to do with the pdf being a form, but a problem that seems to crop up when I repeatedly stamp the same output file. Solution is just to explicity delete the former output file before re-running process.

Related

Show PDF without saving it with itext 7 and vb.net

I currently have the following code, which opens a PDF file and has fillable fields, saves it to a path, and then displays it on the screen (Adobe Reader). What I currently want is to open the PDF, pass the data to it and just display it either in a browser or in Adobe Reader without the need to save it to the local disk.
Dim destino = "C:\generacion\ejemplo.pdf"
Dim leerpdf = "C:\plantillas\plantilla.pdf"
Dim reader As PdfReader = New PdfReader(leerpdf)
Dim writer As PdfWriter = New PdfWriter(CStr(destino))
Dim PdfDocument As PdfDocument = New PdfDocument(reader, writer)
Dim form As iText.Forms.PdfAcroForm = PdfAcroForm.GetAcroForm(PdfDocument, False)
form.GetField("dato1").SetValue(nombre)
form.GetField("dato2").SetValue(direccion)
form.GetField("dato3").SetValue(telefono)
form.FlattenFields()
PdfDocument.Close()
Process.Start(destino)

bitmap image printing using axiohm usbcomm dll

I am using an Axiohm thermal printer for printing POS receipt(USBCOMM.dll for communication). Currently, i am able to print the required details along with an image(.bmp file). Now i need to use a new image instead of the existing image. The new image contains barcode.
When i try printing the new image, all i get is some garbage values. Below is the code that i use. Same code works with old image but not with the new image. Is there any format for image that i need to follow.
Dim filepath As String = AppDomain.CurrentDomain.BaseDirectory + "Resources\PrinterDlls\unnamed.bmp"
Using fs = New FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)
Dim inpt As Byte() = New Byte(fs.Length) {}
inpt(0) = &H1F
fs.Read(inpt, 1, CInt(fs.Length))
Dim ok As Boolean = Usb_WritePort(True, inpt, inpt.Length, written, IntPtr.Zero)
If Not ok OrElse written <> inpt.Length Then
Throw New Exception("USB write failed")
End If
End Using
Well, this is embarrassing that i am answering my own question. I searched for sometime to resolve and raised the question. Soon after, i came across this video in youtube that explain the bitmap image to create for thermal printing
https://www.youtube.com/watch?v=LdB33eWLjgU
Basically, you need to ensure 3 things while creating the image:
1. 8-bit
2. Greyscale
3. Save as .bmp
And the new image will work like a charm while printing. Also ensure the width is less than the paper width.

Cannot find bookmarks from OpenXML appended document

using the following code snippet I open a document template (DOTX) and then append another document. Both have bookmarks.
Dim m_word As WordprocessingDocument = = WordprocessingDocument.Open("FrontPage.dotx", True)
Dim altChunkId As String = "ChunkId1"
Dim mainPart As MainDocumentPart = m_word.MainDocumentPart
Dim chunk As AlternativeFormatImportPart = mainPart.AddAlternativeFormatImportPart(
DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML, altChunkId)
Using fileStream As IO.FileStream = IO.File.Open("Appendix.dotx", IO.FileMode.Open)
chunk.FeedData(fileStream)
End Using
Dim altChunk As AltChunk = New DocumentFormat.OpenXml.Wordprocessing.AltChunk()
altChunk.Id = altChunkId
mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph).Last())
mainPart.Document.Save()
Now if I try to loop trough all bookmarks like this:
Dim docbody As Body = doc.GetFirstChild(Of Body)()
For Each bookmarkStart As BookmarkStart In docbody.Descendants(Of BookmarkStart)()
' Do something with the bookmarks
Next
I only get the bookmarks of the original frontpage.dotx, none of the bookmarks of the appendix.dotx is found.
If I save the document to a file, all the bookmarks are there when I open it using Word. I can also reopen the saved file i C# and then all bookmarks can be found using the above For Each loop. The question is, how can I get all the bookmarks after appending without saving and reloading the document?
When you use AltChunk to embed a document the entire file is embedded into the document - it's NOT integrated. That only happens when the combined document is opened by Word. If you need to work through all the bookmarks you need to either
Open each document, do the bookmarks, and THEN combine the two using AltChunk OR
Not use AltChunk to combine the documents, and transfer the second document part-by-part into the first document.

Add a table to a PDF template using iTextSharp and VB.net

I've been stuck on this far longer than I care to admit. I'm trying to use iTextSharp to build a table that I can then insert into a PDF template (which is really just a PDF with a header and an acrofield that needs to be populated). I've currently got code that follows the same outline below:
Dim doc As New Document
Dim reader As PdfReader
Dim stamper As PdfStamper
Dim filestream As FileStream
Dim tempfile As String = My.Computer.FileSystem.GetTempFileName
filestream = New FileStream(tempfile, FileMode.Create)
PdfWriter.GetInstance(doc, filestream)
doc.Open()
generateTableForPdf(listOfData, numColumns, doc)
doc.Close()
reader = New PdfReader(pdfTemplatePath)
stamper = New PdfStamper(reader, filestream)
stamper.AcroFields.SetField("topmostSubform[0].Page1[0].headerField", "some text to go in the field")
The pdfTemplatePath is a private const that has the template's file path that I am trying to use and generateTableForPdf simply creates a dynamically sized table and puts it in doc (doc is passed by ref). I know the table is created because it displays when the page loads, however, the header in the template doesn't appear. I've looked around and found a couple of examples that use byte streams or memory streams, but my attempts at implementing those methods have failed more dramatically. Any help or guidance in better understanding how to go about this is greatly appreciated.

Itextsharp multiple actions work in Chrome, but not in IE

I looked at this Stackoverflow question, iTextSharp multiple actions for pushbuttonfield, but I still cannot get this working correctly. This is a proof of concept before we buy the iTextSharp license.
So here is the background. I am working on a web forms web application written in vb.net. I open a new browser window to display the PDF in an iframe. The PDF contains form fields, which the user can fill out. At the bottom of the form, there will be a submit button to process the form and a save progress button to save their current changes. After the form is processed/saved, it's supposed to redirect to an HTML page that says "Form Submitted Successfully". I have this all working in Google Chrome, but it's not doing the redirect to the HTML page in IE.
We will be getting LOTS of PDFs from our customers. When I create the PDF forms in Acrobat, I add the 2 buttons to the bottom of the PDF. This ensures the correct placement of the buttons, based on where it fits for that PDF. So the buttons will always have the same names, "btnSaveProgress" and "btnProcessForm".
In the codebehind for the source of the iframe, I have this iTextSharp code:
Using myPdfReader As New PdfReader(strFullFilePathName)
Context.Response.Clear()
Context.Response.ContentType = "application/pdf"
Using stamper As PdfStamper = New PdfStamper(myPdfReader, Response.OutputStream)
stamper.ViewerPreferences = PdfWriter.HideToolbar
Dim hostUrl As String = Request.Url.GetLeftPart(UriPartial.Authority)
Dim btnArray() As String = {"btnSaveProgress", "btnProcessForm"}
Dim intCounter = 0
For Each btnName As String In btnArray
Dim saveButtonField As PushbuttonField = stamper.AcroFields.GetNewPushbuttonFromField(btnName)
Dim pff As PdfFormField = saveButtonField.Field
Dim myAction As PdfAction = PdfAction.CreateSubmitForm("../../Common/Services/StaticFormSubmissionHandler.ashx?submissionType=" & intCounter & "&formID=" & intFormID & "&resultID=" & intResultID & "&templateName=" & Server.UrlEncode(sShortName), Nothing, PdfAction.SUBMIT_EXCL_F_KEY)
myAction.Next(New PdfAction(hostUrl & "/Main/Pages/FormSub.htm"))
'pff.SetAdditionalActions(PdfName.U, myAction)
pff.Action = myAction
stamper.AcroFields.ReplacePushbuttonField(btnName, pff)
intCounter += 1
Next
End Using
End Using
The save/process submission works, but the redirect only works in Chrome. In IE, it makes the iframe blank. I'm not seeing any errors or anything. Also, in IE, the PDF has the menu bars displayed. I understand if this is strictly related to the Reader in the IE browser, and I have no control over it. But it would be nice if the stamper.ViewerPreferences = PdfWriter.HideToolbar would work.
Thank you so much in advance for any advice/input.