Document cannot be converted into iTextSharp.text.Document - asp.net

So I saw this tutorial in codeproject http://www.codeproject.com/Articles/20640/Creating-PDF-Documents-in-ASP-NET. I used the itextsharp in my web project
Dim doc As Document = New Document
PdfWriter.GetInstance(doc, New FileStream("C:\Users\PC\Desktop" + _
"\1.pdf", FileMode.Create))
doc.Open()
doc.Add(New Paragraph("Hello World"))
doc.Close()
Response.Redirect("~/1.pdf")
with this syntax I get errors that 'myProjectName.Document' cannot be converted to 'iTextSharp.text.Document'and open, add ,close is not a member of 'myProjectName.Document'
My current framework is 3.5 . I have downloaded the sample project it was framework 2.0 but can still run when I changed it to 3.5,
Any workaround with my problem?

Looks like your Document is coming from some other namespace, try specifying the namespace explicitly:
dim doc as iTextSharp.text.Document = new iTextSharp.text.Document() 'may need parameters to constructor

Related

vb.net Word Document Replace Strings Images

I am trying to create mail merge process with word document (images, text, html). I am finding help online for a desktop application, but trying to do it from a web aspx page.
here is code I tried
Dim wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True)
Using (wordDoc)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(wordDoc.MainDocumentPart.GetStream)
Using (sr)
docText = sr.ReadToEnd
End Using
Dim regexText As Regex = New Regex("Hello world!")
docText = regexText.Replace(docText, "Hi Everyone!")
Dim sw As StreamWriter = New StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))
Using (sw)
sw.Write(docText)
End Using
End Using
but can not even run. I get an error in visual studio 2015.
Severity Code Description Project File Line Suppression State
Error BC30002 Type 'WordprocessingDocument' is not defined.
Any ideas?
thanks

Append created PDF page with existing PDF file with iTextSharp

I'm currently in the process of creating (what I thought would have been) a really simple method to append two PDF files.
Firstly, my method creates a page that has all of the clients details on it as a digital signature. I had this working fine and saving to a single page PDF file.
However, I now want to append the terms & conditions that they're signing to the bottom of the PDF. The solution I'm coding in uses VB.NET, but you can provide the answer in C# if you prefer because I'm familiar with both. I just seriously cannot get my head around iTextSharps process.
Here is my code currently:
Public Sub CreateDocument() Handles btnCreate.ServerClick
Dim path As [String] = Server.MapPath("PDFs")
Dim document As New Document()
Dim writer As PdfWriter = PdfWriter.GetInstance(document, New FileStream(path + "/" + _AccountNo + "-RegAgreement.pdf", FileMode.Create))
'Removed chunk of code here, just defining content chunks and paragraphs
for the dynamically created page, left in the construction
part which you can see below'
'Construct digitally signed agreement page'
document.Open()
document.NewPage()
document.Add(pHeader)
table.SpacingBefore = 30.0F
table.SpacingAfter = 60.0F
document.Add(table)
pAgreement.SpacingAfter = 20.0F
document.Add(pAgreement)
document.Add(pSignedBy)
document.Add(imgSig)
document.Add(pFooter1)
document.Add(pFooter2)
document.Add(pFooter3)
writer.Close()
document.Close()
Now this is the bit I've added to the end of the above sub to append the PDF. As far as I'm aware, you need to use the PdfCopy to transfer the information from the PDF to a new Document object (In this case, doc). But then, I can't find a way to add these to the dynamically created PDF.
Is there perhaps a way to open it within the copier and then start copying from page 2?
Dim terms As New PdfReader(path + "/termsconditions.pdf")
Dim doc As New Document()
Dim copier As New PdfCopy(doc, New FileStream(path + "/" + _accountNo + "-RegAgreement2.pdf", FileMode.Create))
'Append Ts & Cs'
For i As Integer = 1 To terms.NumberOfPages
Dim importedPage As PdfImportedPage = copier.GetImportedPage(terms, i)
copier.AddPage(importedPage)
Next
terms.Close()
terms.Close()
End Sub
Every solution I've seen so far has used different methods like page stamps or memory streams, but none of them have worked or given me the result I need.
Any help is greatly appreciated!
UPDATE
Okay so after #mkl's suggestion, I have now brought the dynamically generated document back with a reader, however it's returning a null value suggesting that the .PDF is blank, but it isn't. (I have the file in my directory with all the content filled)
Dim copier As New PdfCopy(document, New FileStream(path + "/" + _distNo + "-RegAgreement2.pdf", FileMode.OpenOrCreate))
Dim reader As New PdfReader(path + "/" + _distNo + "-RegAgreement.pdf")
'retrieve dynamic document
Dim dynamicPage As PdfImportedPage = copier.GetImportedPage(reader, 1)
copier.AddPage(dynamicPage)
'Append Ts & Cs
For i As Integer = 1 To terms.NumberOfPages
Dim importedPage As PdfImportedPage = copier.GetImportedPage(terms, i)
copier.AddPage(importedPage)
Next
Is this because it's being done within the same subroutine?
Solved, big thanks to #mkl on this one.
The issues I was facing were because I wasn't creating a Document object for the copier to write to.
Dim doc As New Document()
Dim copier As New PdfCopy(doc, New FileStream(path + "/" + _distNo + "-RegAgreement.pdf", FileMode.Create))
'Open PDF created earlier in subroutine'
Dim reader As New PdfReader(path + "/" + _distNo + "-Signed.pdf")
doc.Open()
'Copy first (And only) page of dynamic PDF'
Dim dynamicPage As PdfImportedPage = copier.GetImportedPage(reader, 1)
copier.AddPage(dynamicPage)
'Append Ts & Cs'
For i As Integer = 1 To terms.NumberOfPages
Dim importedPage As PdfImportedPage = copier.GetImportedPage(terms, i)
copier.AddPage(importedPage)
Next
doc.Close()
terms.Close()
reader.Close()
copier.Close()
'For temporary purposes, delete local file'
'This will be done in output stream in end release'
File.Delete(path + "/" + _distNo + "-Signed.pdf")
Thanks for the help guys. Think I've got the basic procedures of this iTextSharp thing down now!

itextsharp PdfStamper.AcroFields.SetField giving error

I have a PDF containing Chinese, Japanese language. In that PDF I have some input fields. I want to fill this PDF dynamically in C#.net
I am using iTextSharp dll to read pad and successfully read the PDF fields but when I am going to set value with PdfStamper.AcroFields.SetField, it gives me this error
Font 'KozMinPro-Regular' with 'UniJIS-UCS2-H' is not recognized.
To read PDF and getting fields I am using the following code
string pdfTemplate = #"C:\Users\admin\Desktop\test.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
StringBuilder sb = new StringBuilder();
foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
{
sb.Append(de.Key.ToString() + Environment.NewLine);
}
And I am getting all fields successfully.
To fill data in PDF I am using this code
string pdfTemplate = #"C:\Users\admin\Desktop\test.pdf";
string newFile = #"C:\Users\admin\Desktop\newdata_test.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
// set form pdfFormFields
pdfFormFields.SetField("fill_17", "test");
I am facing error on pdfFormFields.SetField method as
Font 'KozMinPro-Regular' with 'UniJIS-UCS2-H' is not recognized.
Please advice what I have to change or how I can resolve this issue.
There are some files missing in your project. In order to use the font 'KozMinPro-Regular' with 'UniJIS-UCS2-H', you need to give iTextSharp access to the metrics files that contain information about that font. These metrics files can be downloaded separately from SourceForge. More specifically, you need the file iTextAsian-dll-2.1.zip that can be found in iTextAsian-all-2.1.zip
Note that this will only work with a recent version of iTextSharp (5.3.0.0 or higher). This iTextAsian DLL won't work with older versions of iTextSharp.

itextsharp error: "The document has no pages."

I set as references three dlls:
itextsharp.dll: the core library
itextsharp.xtra.dll: extra functionality (PDF 2!)
itextsharp.pdfa.dll: PDF/A-related functionality
This project is hosted on http://sourceforge.net/projects/itextsharp/
You can find the latest release here:
http://sourceforge.net/projects/itextsharp/files/itextsharp/
I get an error when executing this code:
On pdfDoc.Close(), "The document has no pages."
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
gv.DataBind()
gv.AllowPaging = "False"
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=Export.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Dim frm As New HtmlForm()
gv.Parent.Controls.Add(frm)
frm.Attributes("runat") = "server"
frm.Controls.Add(gv)
frm.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.[End]()
The class HTMLWorker is deprecated and should no longer be used. HTML to PDF functionality has been replaced by technology called XML Worker. I see that you include itextsharp.xtra and itextsharp.pdfa which are 2 DLLs you don't need. I don't see you including the xmlworker DLL.
As for the exception: when you get the message "The document has no pages", you are trying to create a document without any content (and that doesn't make sense). How is this possible? Well, it all depends on the content of sr. That content is either empty or it contains HTML that can't be interpreted by HTMLWorker.
Extra remark: next to itextpdf.xtra, you wrote (PDF 2!). While the xtra package contains functonality that didn't exist in PDF 1.7, it's not the PDF 2 package. The PDF 2 specification is to be expected at the earliest by the end of 2015 (a more realistic estimation is 2016). At iText, we've already implemented PDF 2.0 functionality based on the draft of the spec, but that functionality is (1) not limited to what is in the xtra package, and (2) not part of a specification that has been publicly released by ISO yet.

How to fill a word document using Visual Basic / Visual C# in ASP.NET

I'm looking for options to fill a Word Document from either Visual Basic, or Visual C#. I'm currently using merge fields, and the code below to fill specific fields in a Word Document, but now I've run into a situation where I need tabular data pushed to MS Word. Is there anyway to take data from a grid view (number of rows is dynamic), and import it into a Word Document Table using a merge field or something of that sort? I have to maintain the format of my template doc, and would like to be able to control the layout of the page ..
Dim templateDoc As String = Server.MapPath("\Userfiles\docs\" & location)
Dim mergePath As String = Server.MapPath("\App_Data\Temp\")
Dim mergeFileName As String = location.Replace("/", "_") & ".docx"
Dim mergeDoc As String = mergePath & "\" & mergeFileName
File.Copy(templateDoc, mergeDoc, True)
Using pkg As Package = Package.Open(mergeDoc, FileMode.Open, FileAccess.ReadWrite)
Dim uri As Uri = New Uri("/word/document.xml", UriKind.Relative)
Dim part As PackagePart = pkg.GetPart(uri)
Dim xmlMainXMLDoc As XmlDocument = New XmlDocument()
xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read))
Dim innerXml As String = xmlMainXMLDoc.InnerXml _
.Replace("«Corporate Legal Name»", businessName) _
.Replace("«Address 1»", mailingAddress1) _
.Replace("«Address 2»", mailingAddress2) _
.Replace("«City»", city)
xmlMainXMLDoc.InnerXml = innerXml
Using partWriter As New StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write))
xmlMainXMLDoc.Save(partWriter)
End Using
pkg.Close()
End Using
You can write out in HTML and save it with a .doc extension and Word will handle it gracefully.
Just like my answer for your question regarding Excel, Office writer will work for you here too!

Resources