I'm new here. I am writing a program and use itextsharp. I would like to import various documents and then save them. Unfortunately I do not get it, the second page is read. The editing of the first page kappt super. Here is my code:
If ComboBox1.SelectedItem = "DPD" Then
Dim oldFile As String = "templates/dpd-schadenformular.pdf"
Dim newFile As String = "output/DPD-Output.pdf"
' Create reader
Dim reader As New PdfReader(oldFile)
Dim size As Rectangle = reader.GetPageSizeWithRotation(1)
Dim document As New Document(size)
' Create the writer
Dim fs As New FileStream(newFile, FileMode.Create, FileAccess.Write)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)
document.Open()
Dim cb As PdfContentByte = writer.DirectContent
' Set the font, color and size properties for writing text to the PDF
Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
cb.SetColorFill(BaseColor.DARK_GRAY)
cb.SetFontAndSize(bf, 8)
' Write text in the PDF
cb.BeginText()
Dim kundennummer As String = "Kundennummer " & Form3.dpdkdnr.Text
Dim trackid1 As String = track1.Text
Dim trackid2 As String = track2.Text
Dim descr As String = beschreibungschaden.Text
Dim warenart As String = paketinhalt.Text
Dim empfnam As String = empfnamebox.Text
Dim empfstr As String = empfstrbox.Text
Dim empfplz As String = empfplzbox.Text
' Set the alignment and coordinates here
cb.ShowTextAligned(1, kundennummer, 360, 638, 0)
cb.ShowTextAligned(1, trackid1, 336, 685, 0)
cb.ShowTextAligned(1, trackid2, 430, 685, 0)
cb.ShowTextAligned(1, descr, 150, 135, 0)
cb.ShowTextAligned(1, warenart, 90, 235, 0)
cb.ShowTextAligned(1, empfnam, 370, 441, 0)
cb.ShowTextAligned(1, empfstr, 370, 416, 0)
cb.ShowTextAligned(1, empfplz, 370, 381, 0)
cb.EndText()
' Put the text on a new page in the PDF
Dim page As PdfImportedPage = writer.GetImportedPage(reader, 1)
cb.AddTemplate(page, 0, 0)
' Close the objects
document.Close()
fs.Close()
writer.Close()
reader.Close()
' -----------------------------------------------
' -----------------------------------------------
' --------------------- DPD Ende ----------------
' -----------------------------------------------
' -----------------------------------------------
End If
About approaches, solutions or help I would be really very happy and thank you in advance
Maurice
Here is a method I use to add new pages to a destination document.
'myarray is the document to be added, mydoc is the document added to
Public Function AdddbFiletoDoc(myarray() As Byte, mydoc As Document, mywriter As PdfWriter, mycb As PdfContentByte)
Dim myreader As New PdfReader(myarray)
Dim numofPages As Integer = myreader.NumberOfPages, mypage As PdfImportedPage
Dim currpage As Integer = 0
Do While currpage < numofPages
currpage += 1
mydoc.SetPageSize(PageSize.A4)
'You can add a flag to the method to determine if you want a new page or not
mydoc.NewPage()
mypage = mywriter.GetImportedPage(myreader, currpage)
mycb.AddTemplate(mypage, 1.0F, 0, 0, 1.0F, 0, 0)
Loop
End Function
Related
I am looking to modify the pdf to add the page number and I cannot find why the variable "cb" is empty.
you can see error on the screen below
Error on the screen : "Object reference not set to an instance of an object"
I just found how to edit pdf and add pages number, here is my code for those who need it.
I copy a file, I count the number of pages, in a while loop I display the number of pages (1/3) then I import the page on which I wanted to add the number of pages.
Public Sub ModifPDF(ByVal annee As Integer, ByVal mois As Integer, ByVal nomFichier As String, ByVal sourceFileList As String)
Dim Col1 As PdfPCell
Dim Col2 As PdfPCell
Dim Font1 As New Font(FontFactory.GetFont(FontFactory.HELVETICA, 1, iTextSharp.text.Font.NORMAL))
Dim Font8 As New Font(FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.NORMAL))
Dim Vide As PdfPCell = New PdfPCell(New Phrase("")) With {
.Border = 0
}
Dim reader As New PdfReader(sourceFileList)
Dim sourceFilePageCount As Integer = reader.NumberOfPages
Dim doc As New Document(reader.GetPageSizeWithRotation(1))
My.Computer.FileSystem.CopyFile(sourceFileList, "C:\test")
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("C:\test", FileMode.Open, FileAccess.Write))
doc.Open()
Dim contentByte As PdfContentByte = writer.DirectContent
Dim pageIndex As Integer = 0
While pageIndex < sourceFilePageCount
pageIndex = pageIndex + 1
doc.SetPageSize(reader.GetPageSize(pageIndex))
Dim TableNota As PdfPTable = New PdfPTable(2)
Dim widthsNota As Single() = New Single() {19.7F, 1.5F}
TableNota.WidthPercentage = 97
TableNota.SetWidths(widthsNota)
Col1 = New PdfPCell(New Phrase(" ", Font8)) With {
.Border = 0
}
TableNota.AddCell(Col1)
Col2 = New PdfPCell(New Phrase("page " & pageIndex & "/" & sourceFilePageCount & "", Font8)) With {
.Border = 0
}
TableNota.AddCell(Col2)
TableNota.AddCell(Vide)
doc.Add(TableNota)
Dim page = writer.GetImportedPage(reader, pageIndex)
Dim rotation = reader.GetPageRotation(pageIndex)
If rotation.Equals(90) Then
contentByte.AddTemplate(page, 0, -0.1F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(pageIndex).Height)
Else
contentByte.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
doc.NewPage()
End While
doc.Close()
End Sub
I need load a pdf, add text and save on a new file.
With this code look work but where i have some images the text in under the image, i can't see it.
What can i do ?
Dim oldFile As String = Application.StartupPath & "\old.pdf"
Dim newFile As String = Application.StartupPath & "\new.pdf"
Dim reader As New PdfReader(oldFile)
Dim size As Rectangle = reader.GetPageSizeWithRotation(1)
Dim document As New Document(size)
Dim wNnumberOfPages As Integer = reader.NumberOfPages
Dim fs As New FileStream(newFile, FileMode.Create, FileAccess.Write)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)
document.Open()
Dim cb As PdfContentByte = writer.DirectContent
Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
Dim wPage As Integer
For wPage = 1 To wNnumberOfPages
Dim _text As String = "TEXT"
Dim Page As PdfImportedPage = writer.GetImportedPage(reader, wPage)
cb.BeginText()
cb.SetFontAndSize(bf, 10)
cb.ShowTextAligned(2, _text, 470, 760, 0)
cb.EndText()
cb.AddTemplate(Page, 0, 0)
document.NewPage()
Next
document.Close()
fs.Close()
writer.Close()
reader.Close()
You first draw the text and then draw the imported page:
Dim Page As PdfImportedPage = writer.GetImportedPage(reader, wPage)
cb.BeginText()
cb.SetFontAndSize(bf, 10)
cb.ShowTextAligned(2, _text, 470, 760, 0)
cb.EndText()
cb.AddTemplate(Page, 0, 0)
Thus, any content in the imported page at the location of your text will cover it.
If instead you first draw the imported page and then the text, your text will be above content from the imported page:
Dim Page As PdfImportedPage = writer.GetImportedPage(reader, wPage)
cb.AddTemplate(Page, 0, 0)
cb.BeginText()
cb.SetFontAndSize(bf, 10)
cb.ShowTextAligned(2, _text, 470, 760, 0)
cb.EndText()
That being said, if you want to merely stamp something onto pages of an existing PDF, you should use the PdfStamper instead of PdfWriter with GetImportedPage. The PdfStamper class explicitly is made for such tasks and copies everything from the source document very faithfully. Your approach, on the other hand, drops all interactive and metadata content from the original PDF.
I am able to print PDF using VB.Net on Button click Event. But what i want is to print only Second page of my PDF.
Please help How can i do this.
Dim MyProcess As New Process
MyProcess.StartInfo.CreateNoWindow = False
MyProcess.StartInfo.Verb = "print"
MyProcess.StartInfo.FileName = "D:\765.pdf"
MyProcess.Start()
MyProcess.WaitForExit(10000)
MyProcess.CloseMainWindow()
MyProcess.Close()
Below Is the Function I have used to Extract Number of Pages required to print from the existing PDF
Private Shared Sub ExtractPages(inputFile As String, outputFile As String, start As Integer, [end] As Integer)
' get input document
Dim inputPdf As New PdfReader(inputFile)
' retrieve the total number of pages
Dim pageCount As Integer = inputPdf.NumberOfPages
If [end] < start OrElse [end] > pageCount Then
[end] = pageCount
End If
' load the input document
Dim inputDoc As New Document(inputPdf.GetPageSizeWithRotation(1))
' create the filestream
Using fs As New FileStream(outputFile, FileMode.Create)
' create the output writer
Dim outputWriter As PdfWriter = PdfWriter.GetInstance(inputDoc, fs)
inputDoc.Open()
Dim cb1 As PdfContentByte = outputWriter.DirectContent
' copy pages from input to output document
For i As Integer = start To [end]
inputDoc.SetPageSize(inputPdf.GetPageSizeWithRotation(i))
inputDoc.NewPage()
Dim page As PdfImportedPage = outputWriter.GetImportedPage(inputPdf, i)
Dim rotation As Integer = inputPdf.GetPageRotation(i)
If rotation = 90 OrElse rotation = 270 Then
cb1.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, _
inputPdf.GetPageSizeWithRotation(i).Height)
Else
cb1.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, _
0)
End If
Next
inputDoc.Close()
End Using
I am trying to use itextsharp to take dynamic information and generate a PDF with it.. The PDF's use a background Image on each page which is different and the text content is positioned where it needs to be using the contentByte helper. Thats the plan anyways. I hit a hang up when I tried to add another page and then drop the image and text onto that page... My first page ends up with the image that should be on my second page and the first page image fails to display at all on either page... My code so far is as follows:
Function ID_and_Parking(ByVal id As Integer) As ActionResult
Dim _reg_info As reg_info = db.reg_info.Single(Function(r) r.id = id)
Dim _conf_info As conf_info = db.conf_info.Single(Function(f) f.id = 0)
Dim _name As String = String.Empty
If Not String.IsNullOrWhiteSpace(_reg_info.name_tag_pref) Then
_name = _reg_info.name_tag_pref
Else
_name = _reg_info.first_name + " " + _reg_info.last_name
End If
Dim _LastName As String = _reg_info.last_name
Dim _Employer As String = _reg_info.business_name
Dim _Class_1 As String = _reg_info.tues_class
Dim _Class_2 As String = _reg_info.wed_class
Dim _Class_3 As String = _reg_info.thur_class
Dim _Class_4 As String = _reg_info.fri_class
Dim _BeginDate As String = _conf_info.conf_start_date
Dim _endDate As String = _conf_info.conf_end_date
Dim _dates As String = _BeginDate + "-" + _endDate
If IsDBNull(_reg_info.tues_class) Then
_Class_1 = ""
End If
If IsDBNull(_reg_info.wed_class) Then
_Class_2 = ""
End If
If IsDBNull(_reg_info.thur_class) Then
_Class_3 = ""
End If
If IsDBNull(_reg_info.fri_class) Then
_Class_4 = ""
End If
Dim pdfpath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\PDF_Files\"
Dim imagepath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\PDF_Files\"
Dim _PdfName As String = _LastName + ".pdf"
Dim doc As New Document
doc.SetPageSize(iTextSharp.text.PageSize.LETTER)
doc.SetMargins(0, 0, 0, 0)
Dim _PnameFont As iTextSharp.text.Font = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 18, iTextSharp.text.Font.NORMAL)
Dim BF_Times As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)
Dim _Parking_Name As New Font(BF_Times, 18, Font.NORMAL, BaseColor.BLACK)
Dim _Parking_Date As New Font(BF_Times, 24, Font.BOLD, BaseColor.BLACK)
Try
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(pdfpath + _PdfName, FileMode.Create))
doc.Open()
Dim jpg As Image = Image.GetInstance(imagepath + "/Parking_Pass.jpg")
jpg.Alignment = iTextSharp.text.Image.UNDERLYING
jpg.ScaleToFit(612, 792)
doc.add(jpg)
Dim cb As PdfContentByte = writer.DirectContent
'Render Parking Permit
cb.BeginText()
cb.SetFontAndSize(BF_Times, 16)
cb.SetTextMatrix(145, 135.5)
cb.ShowText(_BeginDate)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 16)
cb.SetTextMatrix(429, 135.5)
cb.ShowText(_endDate)
cb.EndText()
Dim _idJpg As Image = Image.GetInstance(imagepath + "/Id_Tag.jpg")
Dim imageWidth As Decimal = _idJpg.Width
Dim imageHeight As Decimal = _idJpg.Height
doc.SetPageSize(iTextSharp.text.PageSize.LETTER)
_idJpg.Alignment = iTextSharp.text.Image.UNDERLYING
_idJpg.ScaleToFit(612, 792)
doc.NewPage()
doc.Add(_idJpg)
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(100, 50)
cb.ShowText(_name)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(200, 100)
cb.ShowText(_Employer)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(300, 150)
cb.ShowText(_Class_1)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(310, 50)
cb.ShowText(_Class_2)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(320, 50)
cb.ShowText(_Class_3)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(330, 50)
cb.ShowText(_Class_4)
cb.EndText()
doc.Close()
Catch dex As DocumentException
Response.Write(dex.Message)
Catch ioex As IOException
Response.Write(ioex.Message)
Catch ex As Exception
Response.Write(ex.Message)
End Try
Return RedirectToAction("showUserPDF", New With {.pdfName = _PdfName})
End Function
I have been all over every forum about this but all of the information I have found seems to be off from what I am looking for, OR maybe I am just going about this the wrong was all together... Any help would be greatly appreciated...
In your code you've got this:
Dim jpg As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath + "/Parking_Pass.jpg")
jpg.Alignment = iTextSharp.text.Image.UNDERLYING
jpg.ScaleToFit(612, 792)
But you are never actually adding jpg to the doc
I actually have figured out the issue I overlooked my placement of the newpage and the image placement... I had the 2nd page image before the newpage... Thanks for your help... If anyone else neededs to dynamically fill a image with data the above solution works...
I have created a simple table and i need to position. does anyone have experience with tables in itextsharp?
here's my code
Private Sub generate_PDF()
Directory.SetCurrentDirectory("C:\Users\alexluvsdanielle\Desktop\")
Console.WriteLine("Chapter 6 example 1: Adding a Wmf, Gif, Jpeg and Png-file using urls")
Dim document As Document = New Document
Try
Dim writer As PdfWriter = PdfWriter.GetInstance(document, New FileStream("Chap1002.pdf", FileMode.Create))
document.Open()
'Dim wmf As Image = Image.GetInstance("harbour.wmf")
'Dim gif As Image = Image.GetInstance("vonnegut.gif")
Dim jpeg As Image = Image.GetInstance("C:\Users\alexluvsdanielle\Desktop\test.jpg")
'Dim png As Image = Image.GetInstance("hitchcock.png")
'document.Add(wmf)
'document.Add(gif)
jpeg.ScalePercent(50)
'jpeg.Alignment = Image.TOP_BORDER
jpeg.SetAbsolutePosition(0, 562)
document.Add(jpeg)
'document.Add(png)
Dim cb As PdfContentByte = writer.DirectContent
cb.BeginText()
Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
cb.SetFontAndSize(bf, 12)
'Dim text As String = "Sample text for alignment"
'cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, text + " Center", 250, 700, 0)
'cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, text + " Right", 250, 650, 0)
'cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text + " Left", 250, 600, 0)
cb.SetTextMatrix(150, 652)
cb.ShowText(patient_name)
cb.SetTextMatrix(150, 637)
cb.ShowText(doc_name)
cb.SetFontAndSize(bf, 8)
cb.SetTextMatrix(150, 620)
cb.ShowText(lot__no)
cb.SetTextMatrix(150, 611)
cb.ShowText(patient_id)
Dim i As Integer
For i = 1 To 10
cb.SetTextMatrix(150, 600 - (i * 10))
cb.ShowText(DataGridView1.Item(3, i).Value)
Next
cb.EndText()
Dim aTable As Table = New Table(2, 2)
aTable.Offset = 10
aTable.Width = 100
aTable.AddCell("0.0")
aTable.AddCell("0.1")
aTable.AddCell("1.0")
aTable.AddCell("1.1")
document.Add(aTable)
Dim datatable As PdfPTable = New PdfPTable(12)
Dim page As Rectangle = document.PageSize
datatable.TotalWidth = 100
datatable.AddCell("hello")
datatable.WriteSelectedRows(0, -1, document.LeftMargin, document.BottomMargin, writer.DirectContent)
document.Add(datatable)
Catch de As DocumentException
Console.Error.WriteLine(de.Message)
MessageBox.Show(de.Message)
Catch ioe As IOException
Console.Error.WriteLine(ioe.Message)
MessageBox.Show(ioe.Message)
Catch e As Exception
Console.Error.WriteLine(e.Message)
MessageBox.Show(e.Message)
End Try
document.Close()
End Sub
the first table works but the second does not
You can do something like this:
PdfPTable foot = new PdfPTable(2);
foot.TotalWidth = page.Width - document.LeftMargin - document.RightMargin;
foot.WriteSelectedRows(0, -1, document.LeftMargin, document.BottomMargin,
writer.DirectContent);
Make sure your code is closing the document and initializing the PdfWriter.
Example of what I use (output path is a variable passed into the function in C#):
Document document = new Document();
var writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create));
document.Open();
//write stuff here
document.Close();