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
Related
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
I'm merging two pdf into one i'm using a function that I found here
Private Sub MergePdfFiles(ByVal pdfFiles() As String, ByVal outputPath As String)
Dim pdfCount As Integer = 0
Dim f As Integer = 0
Dim fileName As String
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim pageCount As Integer = 0
Dim pdfDoc As iTextSharp.text.Document = Nothing
Dim writer As PdfWriter = Nothing
Dim cb As PdfContentByte = Nothing
Dim page As PdfImportedPage = Nothing
Dim rotation As Integer = 0
Try
pdfCount = pdfFiles.Length
If pdfCount > 1 Then
fileName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fileName)
pageCount = reader.NumberOfPages
pdfDoc = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18)
writer = PdfWriter.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))
With pdfDoc
.Open()
End With
cb = writer.DirectContent
While f < pdfCount
Dim i As Integer = 0
While i < pageCount
i += 1
pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i))
pdfDoc.NewPage()
page = writer.GetImportedPage(reader, i)
rotation = reader.GetPageRotation(i)
If rotation = 90 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height)
ElseIf rotation = 270 Then
cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
End While
f += 1
If f < pdfCount Then
fileName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fileName)
pageCount = reader.NumberOfPages
End If
End While
pdfDoc.Close()
reader.Close()
End If
Catch ex As Exception
'err
End Try
End Sub
Now I need to delete the old files "pdfFiles()" but I'm getting the error "The process cannot access the file 'C:.......pdf' because it is being used by another process." this is only happening with the first file, I have no problem with the other one
OP Here with the function
Thanks
I know this is in C# but this is what i use to merge files together.
var document = new Document();
var outFile = Path.Combine(finishedFilePath, fileName + ".pdf");
var writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
try
{
document.Open();
foreach (var fileName in filesList)
{
var reader = new PdfReader(Path.Combine(StartPath, fileName));
for (var i = 1; i <= reader.NumberOfPages; i++)
{
var page = writer.GetImportedPage(reader, i);
writer.AddPage(page);
}
reader.Close();
}
writer.Close();
document.Close();
}
catch (Exception ex)
{
//catch error
}
finally
{
writer.Close();
document.Close();
}
Hope this helps in some way.
The code that was marked correct is in C# here is the vb.net version:
Public Sub MergePDFFiles(ByVal outPutPDF As String)
Dim StartPath As String = FileArray(0) ' this is a List Array declared Globally
Dim document = New Document()
Dim outFile = Path.Combine(outPutPDF)' The outPutPDF varable is passed from another sub this is the output path
Dim writer = New PdfCopy(document, New FileStream(outFile, FileMode.Create))
Try
document.Open()
For Each fileName As String In FileArray
Dim reader = New PdfReader(Path.Combine(StartPath, fileName))
For i As Integer = 1 To reader.NumberOfPages
Dim page = writer.GetImportedPage(reader, i)
writer.AddPage(page)
Next i
reader.Close()
Next
writer.Close()
document.Close()
Catch ex As Exception
'catch a Exception if needed
Finally
writer.Close()
document.Close()
End Try
End Sub
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'm trying to export a populated datagridview with the following code:
Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel
Imports System.Drawing
Imports DGVPrinterHelper
Imports iTextSharp
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports System.Data.Odbc
Imports System.IO
Private Sub Export_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName = "" Then
MsgBox("Enter Filename to create PDF")
Exit Sub
Else
ExportDataToPDFTable()
MsgBox("PDF Created Successfully")
End If
End Sub
Private Function GetDataTable() As DataTable
Dim dataTable As New Data.DataTable("MyDataTable")
'Create another DataColumn Name
For column As Integer = 1 To DataGridView1.ColumnCount - 1
Dim dataColumn_1 As New DataColumn(DataGridView1.Columns(column).HeaderText.ToString(), GetType(String))
dataTable.Columns.Add(dataColumn_1)
'Now Add some row to newly created dataTable
Dim dataRow As DataRow
For i As Integer = 0 To DataGridView1.Rows.Count - 1
dataRow = dataTable.NewRow()
' Important you have create New row
dataRow(DataGridView1.Columns(column).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(column).Value.ToString()
dataTable.Rows.Add(dataRow)
Next i
Next column
dataTable.AcceptChanges()
Return dataTable
End Function
Private Sub ExportDataToPDFTable()
Dim paragraph As New Paragraph
Dim doc As New Document(iTextSharp.text.PageSize.A4, 40, 40, 40, 10)
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(SaveFileDialog1.FileName + ".pdf", FileMode.Create))
doc.Open()
Dim font12BoldRed As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.UNDERLINE Or iTextSharp.text.Font.BOLDITALIC, BaseColor.RED)
Dim font12Bold As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
Dim font12Normal As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK)
Dim p1 As New Phrase
p1 = New Phrase(New Chunk("PDF From Datagridview Data", font12BoldRed))
doc.Add(p1)
'Create instance of the pdf table and set the number of column in that table
Dim PdfTable As New PdfPTable(5)
PdfTable.TotalWidth = 490.0F
'fix the absolute width of the table
PdfTable.LockedWidth = True
'relative col widths in proportions - 1,4,1,1 and 1
Dim widths As Single() = New Single() {1.0F, 4.0F, 1.0F, 1.0F, 1.0F}
PdfTable.SetWidths(widths)
PdfTable.HorizontalAlignment = 1 ' 0 --> Left, 1 --> Center, 2 --> Right
PdfTable.SpacingBefore = 2.0F
'pdfCell Decleration
Dim PdfPCell As PdfPCell = Nothing
'Assigning values to each cell as phrases
PdfPCell = New PdfPCell(New Phrase(New Chunk("Taxcode", font12Bold)))
'Alignment of phrase in the pdfcell
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
'Add pdfcell in pdftable
PdfTable.AddCell(PdfPCell)
PdfPCell = New PdfPCell(New Phrase(New Chunk("Tax Name", font12Bold)))
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
PdfTable.AddCell(PdfPCell)
PdfPCell = New PdfPCell(New Phrase(New Chunk("Cess Tax", font12Bold)))
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
PdfTable.AddCell(PdfPCell)
PdfPCell = New PdfPCell(New Phrase(New Chunk("Sales Tax", font12Bold)))
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
PdfTable.AddCell(PdfPCell)
PdfPCell = New PdfPCell(New Phrase(New Chunk("Other Tax", font12Bold)))
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
PdfTable.AddCell(PdfPCell)
Dim dt As DataTable = GetDataTable()
If dt IsNot Nothing Then
'Now add the data from datatable to pdf table
For rows As Integer = 0 To dt.Rows.Count - 1
For column As Integer = 0 To dt.Columns.Count - 1
PdfPCell = New PdfPCell(New Phrase(dt.Rows(rows)(column).ToString(), font12Normal))
If column = 0 Or column = 1 Then
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT
Else
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT
End If
PdfTable.AddCell(PdfPCell)
Next
Next
'Adding pdftable to the pdfdocument
doc.Add(PdfTable)
End If
doc.Close()
End Sub
When I run the program a click the button it prompts me with the SaveFileDialog, but once I click save I get the error "Unable to cast object of type 'System.Data.DataTable' to type 'Microsoft.Office.Interop.Excel.DataTable'." at the "Return dataTable" line in the Private Function GetDataTable(). Can anyone help me resolve this issue? And please feel free to point out other errors with my code (if there are any)
I can't figure out the solution. This is my code:
Dim wbRect As Rectangle = WebBrowser1.ClientRectangle
Dim wbBm As New Bitmap(WebBrowser1.ClientRectangle.Width, WebBrowser1.ClientRectangle.Height)
Dim gwb As Graphics = Graphics.FromImage(wbBm)
gwb.CopyFromScreen(WebBrowser1.PointToScreen(New Point(14, 31)),
New Point(0, 0),
New Size(PictureBox1.Width, PictureBox1.Height))
wbBm.Save("c:\temp1.bmp")
PictureBox1.ImageLocation = "c:\temp1.bmp"
PictureBox1.BringToFront()
Dim bm As New Bitmap("c:\img1.bmp") //here appears an error - Parameter is not valid
Dim rect As New Rectangle(0, 0, bm.Width, bm.Height)
Dim bmpData As System.Drawing.Imaging.BitmapData = bm.LockBits(rect, _
System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
What could I do to remove the error?
You will get this error if the file does not exist. Check to make sure img1.bmp exists before you try and open it:
Dim fn As String = "c:\img1.bmp"
If File.Exists(fn)
Dim bm As New Bitmap(fn) ''here appears an error - Parameter is not valid
Dim rect As New Rectangle(0, 0, bm.Width, bm.Height)
Dim bmpData As System.Drawing.Imaging.BitmapData = bm.LockBits(rect, _
System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
End If