Stamp rotated text using itext7 in vb.net - vb.net

I'm trying to convert some itextsharp code to use itext7 which stamps text on each page of a pdf at rotate 90 degrees. Unfortunately all the examples I can find are in c# and while I can use an online translator I'm having difficulties with this one.
The below code stamps my text on at the specified coords on each page of a given pdf:
Shared Sub itext7_stamp_text_on_pdf(mypdfname As String, myfoldername As String)
Dim src As String = myfoldername & "\" & mypdfname
Dim dest As String = myfoldername & "\Stamped " & mypdfname
Dim pdfDoc As PdfDocument = New PdfDocument(New PdfReader(src), New PdfWriter(dest))
Dim document As Document = New Document(pdfDoc)
Dim canvas As PdfCanvas
Dim n As Integer = pdfDoc.GetNumberOfPages()
For i = 1 To n
Dim page As PdfPage = pdfDoc.GetPage(i)
canvas = New PdfCanvas(page)
With canvas
.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 12)
.BeginText()
.MoveText(100, 100)
.ShowText("SAMPLE TEXT 100,100")
.EndText()
End With
Next
pdfDoc.Close()
End Sub
... but I can't see a way of rotating it to 90 degrees.
There's an example here if you use a paragraph:
https://kb.itextpdf.com/home/it7kb/examples/itext-7-building-blocks-chapter-2-rootelement-examples#iText7BuildingBlocksChapter2:RootElementexamples-c02e14_showtextaligned
... but I can't seem to translate this to vb.net. I can specify where the errors I get are, but I thought I'd be better asking this general question first in case there's a way to do this without using a paragraph.
Can anyone help please?
Thanks!

Well, after some more digging this code seems to work OK on the rotation part:
Dim pdf As New PdfDocument(New PdfReader(inpdf), New PdfWriter(outpdf))
Dim document As New Document(pdf)
document.ShowTextAligned("This is some test text", 400, 750, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 0.5F * CSng(Math.PI))
document.Close()
End Sub
.... but it gets hidden behind existing content, so I need a way to make sure it's set to over content.

Related

Winnovative Hides Text of TextElements on PDFs

There is a group somewhere in our organization that scans documents and converts them to PDFs. They then associate those PDFs with an "event" record and store them in a database. On demand, my application -- which uses Winnovative HTML to PDF v9.0.0.0 -- has to retrieve the PDFs associated with an event, place a header on the first page of each, and store them on the file system. This header is a TextElement.
On some PDFs, the header displays beautifully. On others, the header does not appear. However, when viewing the PDF, the header can be "highlighted" with the cursor and its text successfully copied, so the header is indeed present and properly positioned. (See the green arrow in the inserted image.)
I have identified two PDFs that were scanned by the same person thirty minutes apart and associated with the same event in the database. On one, the header is displayed; on the other, it is not. To investigate, I have set the BackColor of the TextElement to Crimson. The Text appears and doesn't appear as before, but the TextElement always appears bright red.
The properties of the two Document and PDFPage objects are identical, including the TransparencyEnabled property. This phenomenon is present in PDFs of all sorts of documents scanned by various people over time. And it's not just this header TextElement, but TextElements everywhere on the PDF (e.g. Page X of Y, watermarks). On a given PDF, if the Text of one is visible, the Text of all is visible, and vice versa.
I can find no pattern or explanation. What could be causing some PDFs to "hide" the Text (and only the Text) of all TextElements that I put on them while others don't?
Private Sub AddTitleToFirstPage(ByRef pdf As Document)
Dim headerSystemFont As New Font("Arial", 10)
Dim headerFont As PdfFont = pdf.Fonts.Add(headerSystemFont)
Dim headerTextElement As New TextElement(65, 20, "My Page Title", headerFont)
headerTextElement.TextAlign = HorizontalTextAlign.Center
headerTextElement.ForeColor = Color.DarkBlue
headerTextElement.BackColor = Color.Crimson
pdf.Pages(0).AddElement(headerTextElement)
End Sub
Friend Function UpdatePdfDoc(pdfBytes As Byte()) As Byte()
Dim bytes As Byte()
Using docStream As New MemoryStream(pdfBytes, 0, pdfBytes.Length)
Dim returnDoc As Document = New Document(docStream)
returnDoc.LicenseKey = WinnovativeLicenceKey
AddTitleToFirstPage(returnDoc)
bytes = returnDoc.Save()
docStream.Close()
End Using
Return bytes
End Function
Friend Function GetEventObjectPdfSource(scannedDocIds As List(Of String)) As Object
Dim scannedDocObjectPdfSourceList As New List(Of Byte())()
For Each scannedDocId As String In scannedDocIds
Dim scannedDocObjectPdfSource As Byte() = GetScannedDocBlobById(scannedDocId)
scannedDocObjectPdfSource = UpdatePdfDoc(scannedDocObjectPdfSource)
scannedDocObjectPdfSourceList.Add(scannedDocObjectPdfSource)
Next
Return scannedDocObjectPdfSourceList
End Function
Friend Function GetEventObjectPdf(eventId As String) As String
Dim pdfFileName As String = GetPDFFileName(eventId)
Dim scannedDocIds As List(Of String) = GetScannedDocumentsForEvent(eventId)
Dim objectPdfSourceList As List(Of Byte()) = CType(GetEventObjectPdfSource1(scannedDocIds), List(Of Byte()))
For Each objectPdfSource As Byte() In objectPdfSourceList
Using docStream As New MemoryStream(objectPdfSource, 0, objectPdfSource.Length)
Dim masterDoc As New Document(docStream)
masterDoc.LicenseKey = WinnovativeLicenceKey
Do While masterDoc.Bookmarks.Count > 0
masterDoc.Bookmarks.Remove(0)
Loop
Try
masterDoc.AutoCloseAppendedDocs = True
masterDoc.Save(pdfFileName)
Catch ex As Threading.ThreadAbortException
Threading.Thread.ResetAbort()
Finally
masterDoc.DetachStream()
masterDoc.Close()
End Try
docStream.Close()
End Using
Next
Return pdfFileName
End Function
Please forgive the clunky code. I didn't write it. I just inherited it.

How to make invisible text visible with iText 4 in an existing pdf

I have a PDF which is created by scanning software. One image per page and hidden OCR'ed text.
I want to remove the images and make the text visible.
I found info how to remove images (replace by another image) but found no way for making the invisible text visible.
Sample PDF with image and hidden text
I tried below method, but it does not work:
Public Shared Sub UnhideText(ByVal strFileName As String)
Dim pdf As iTextSharp.text.pdf.PdfReader = New iTextSharp.text.pdf.PdfReader(strFileName)
Dim stp As iTextSharp.text.pdf.PdfStamper = New iTextSharp.text.pdf.PdfStamper(pdf, New IO.FileStream("e:\out.pdf", IO.FileMode.Create))
'This does not work, text remains unvisible. I guess SetTextRenderingMode applies only for new added text.
For pageNumber As Integer = 1 To pdf.NumberOfPages
Dim cb As iTextSharp.text.pdf.PdfContentByte = stp.GetOverContent(pageNumber)
cb.SetTextRenderingMode(iTextSharp.text.pdf.PdfContentByte.TEXT_RENDER_MODE_FILL)
Next
stp.Close()
End Sub

Increase page size in PDF documents to fit barcode (itextsharp)

I'm using vb.net to build a workflow where I'm processing a number of PDF files. One of the things I need to do is to place a barcode in the bottom left corner of the first page on each PDF document.
I already worked out the code to place the barcode but the problem is that it may cover existing content on the first page.
I want to increase the page size and add about 40 pixels of white space at the bottom of the first page where I can place the barcode. But I dont know how to do this!
Here is the existing code:
Public Sub addBarcodeToPdf(byval openPDFpath as string, byval savePDFpath as string, ByVal barcode As String)
Dim myPdf As PdfReader
Try
myPdf = New PdfReader(openPDFpath)
Catch ex As Exception
logEvent("LOAD PDF EXCEPTION " & ex.Message)
End Try
Dim stamper As PdfStamper = New PdfStamper(myPDF, New FileStream(savePDFpath, FileMode.Create))
Dim over As PdfContentByte = stamper.GetOverContent(1)
Dim textFont As BaseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
Dim BarcodeFont As BaseFont = BaseFont.CreateFont("c:\windows\fonts\FRE3OF9X.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED)
over.SetColorFill(BaseColor.BLACK)
over.BeginText()
over.SetFontAndSize(textFont, 15)
over.SetTextMatrix(30, 3)
over.ShowText(barcode)
over.EndText()
over.BeginText()
over.SetFontAndSize(BarcodeFont, 28)
over.SetTextMatrix(5, 16)
over.ShowText("*" & barcode & "*")
over.EndText()
stamper.Close()
myPdf.Close()
End Sub
Thank you in advance!
/M
Thank you Bruno for pointing me in the right direction. I haven't done volume testing yet but I managed to get it work on one PDF sample. Just changing the mediabox was not enough (I could only make the page size smaller) but when changing the cropbox at the same thime I got the results I was looking for.
Code in VB below for reference
Dim myPdf As PdfReader
Try
myPdf = New PdfReader(openPDFpath)
Catch ex As Exception
logEvent("LOAD PDF EXCEPTION " & ex.Message)
End Try
Dim stamper As PdfStamper = New PdfStamper(myPdf, New FileStream(savePDFpath, FileMode.Create))
Dim pageDict As PdfDictionary = myPdf.GetPageN(1)
Dim mediabox As PdfArray = pageDict.GetAsArray(PdfName.MEDIABOX)
Dim cropbox As PdfArray = pageDict.GetAsArray(PdfName.CROPBOX)
Dim pixelsToAdd As Integer = -40
mediabox.Set(1, New PdfNumber(pixelsToAdd))
cropbox.Set(1, New PdfNumber(pixelsToAdd))
stamper.Close()
myPdf.Close()
Thanks
/M

Controlling Image Resolution when coverting a PNG image into a PDF using iTextSharp

I have created a PNG image that is 200 DPI, and perfectly sized for a landscape A4 page size. I needed to convert this to a PDF document, so I've used the iTextSharp library with the code below.
This all works, however the image quality has degraded. Any suggestions as to how I might improve this?
Public Sub ConvertPNGtoPDF(ByVal inputFile As String, ByVal outputFile As String)
Using fs As New FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)
Dim document As New Document(PageSize.A4.Rotate, 0, 0, 0, 0)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)
document.Open()
Dim cb As PdfContentByte = writer.DirectContent
Using bm As New Bitmap(inputFile)
Dim total As Integer = bm.GetFrameCount(FrameDimension.Page)
For k As Integer = 0 To total - 1
bm.SelectActiveFrame(FrameDimension.Page, k)
Dim img As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(bm, Nothing, False)
img.SetDpi(200, 200)
img.ScalePercent(72.0F / 200.0F * 100)
img.SetAbsolutePosition(0, 0)
cb.AddImage(img)
document.NewPage()
Next
End Using
document.Close()
writer.Close()
End Using
End Sub
This all works, however the image quality has degraded. Any suggestions as to how I might improve this?
Looking at the code in PngImage, it looks like iText doesn't support PNG compression as a PDF-native filter, so it has to be decompressed and recompressed as Something Else. Is this because the PDF spec doesn't support it:
Just checked, sure looks that way.
Best fix? JPEG and JPEG2000 are supported as "native" compression types within PDF (and this is echoed in iText[sharp]). So use JPEG[2k] instead, and run your images through your image conversion library of choice if need be.

How to write string data to tiff file in vb.net

I need to write some data which is string to tiff file. I am doing in the following way
Dim OFile As System.IO.File
Dim OWrite As system.IO.TextWriter
OWrite = OFile.CreateText("Signature.tiff")
OWrite.Write(ControlData)
MessageBox.Show("Signature is recieved and it is saved in Signature.tiff")
ControlData is the string which is to be written to the file.
I am capturing the signature from the user. This function gets the data in string format and i need to create a tiff file using the string data.
When i did in this way, signature.tiff is created but when i opened the image it is giving no preview available.
Can you tell me what is the problem or correct way of doing this?
Thanks a lot.
Dim format As StringFormat = New StringFormat()
Dim MyRect As Rectangle = New Rectangle(0, 0, 400, 400)
Dim MyGraphics As Graphics = Me.CreateGraphics()
Dim MyImg As Image = New Bitmap(MyRect.Width, MyRect.Height, MyGraphics)
Dim imageGraphics As Graphics = Graphics.FromImage(MyImg)
imageGraphics.FillRectangle(Brushes.White, MyRect)
format.Alignment = StringAlignment.Center
format.LineAlignment = StringAlignment.Center
imageGraphics.DrawString("Hello Everyone", objFont, Brushes.Black, RectangleF.op_Implicit(MyRect))
MyGraphics.DrawImage(MyImg, MyRect)
MyImg.Save(filename)
Just see this may help you all for converting text string to image.
Thanks.
TIFF files are binary image files. You are writing the string to a text file. Try opening the file in Notepad to check.
You need a way to create an image in memory and save it to TIFF format.
You could use a PictureBox control. Write the string onto the PictureBox then save as a TIFF.