Merging Jpg file to Pdf Stream - asp.net

Here is my issue: I'm trying to read JPG files from a folder and convert them to one PDF file for example if in my folder I have 1).Hello.jpg 2). World.jpg I want to grab those files and combined it to a one PDF file so the result will be
newPDF.pdf
I'm reading the images correctly from the folder adding them to the document but it's not creating the new PDF file in the folder. How can I solve this??
Here is my code:
'!=Orginally after setting all the files in the folder we need to read the path from the session file.
'!= After reading the path we need to read each file from the folder and generate one pdf file.
Dim attachmentsFolder As String = "E:/IRAttachments/PSC/2013/2/IR-7264"
Dim fileName As String = String.Concat("IR_7264(", DateTime.Now.ToString("yyyyMMddHHmmssfff").ToString(), ").pdf")
Dim finalPathName As String = String.Concat(attachmentsFolder, "/", fileName)
'!= Step 2). read the pdf/images from folder and merge them to a one pdf file.
Dim files As New List(Of String)()
Dim readerList As New List(Of PdfReader)()
m_HashTableIRAttachments = New Hashtable
m_DictionaryEntryIRAttachments = New DictionaryEntry
Dim fileExtentionType As String = String.Empty
Dim doc As Document = New Document
For Each filePath As String In Directory.GetFiles(attachmentsFolder)
fileExtentionType = filePath.Substring(filePath.LastIndexOf("."))
If fileExtentionType = ".jpg" Then '# Get the extension type
Dim document As New Document()
Using stream = New FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)
PdfWriter.GetInstance(document, stream)
document.Open()
Using imageStream = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim image__1 = Image.GetInstance(imageStream)
document.Add(image__1)
Dim pdfFile As String = finalPathName
End Using
document.Close()
End Using
'PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + fileName, FileMode.Create))
'doc.Open()
'doc.Add(New Paragraph("Hello World"))
'Dim myDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
'Dim pdfFile As String = finalPathName
'Dim writer As PdfWriter = PdfWriter.GetInstance(myDoc, New FileStream(pdfFile, FileMode.Create))
'myDoc.Open()
'Dim para As New Paragraph("Let's write some text before inserting image.")
'Dim myImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(filePath)
'myImage.ScaleToFit(300.0F, 250.0F)
'myImage.SpacingBefore = 50.0F
'myImage.SpacingAfter = 10.0F
'myImage.Alignment = Element.ALIGN_CENTER
'myDoc.Add(para)
'myDoc.Add(myImage)
'myDoc.Close()
'doc.Close()
Else
'# Means it's a pdf and not a jpg file.
Dim pdfReader1 As New PdfReader(filePath)
readerList.Add(pdfReader1)
End If
Next

When you create the Stream for your PDF file, you are using the fileName variable, which is only the name, not the full path. It is likely that the PDF is being created - just not where you are expecting it to be. You probably want to use finalPathName instead:
Using stream = New FileStream(finalPathName, FileMode.Create, FileAccess.Write, FileShare.None)
I would also recommend you take a look at the methods available on the System.IO.Path class, and use them when constructing file paths and getting the file extension, e.g.
Dim finalPathName As String = Path.Combine(attachmentsFolder, fileName)
'...
fileExtentionType = Path.GetExtension(filePath)
' etc.
EDIT
It looks like you are also overwriting the PDF file for each image file, while I would imagine you want all of the images in one PDF file. Your loop for the images should probably be inside the Using stream = ... block (e.g. between document.Open() and document.Close()).

Related

How to get the contents a particular cell using excel data reader in Visual Basic? Using ExcelData Reader

I'm using the following code and I'm trying to understand how to access the content of each cell in the excel document in order to Validate it... but everything that I've found on the internet is in C# I tried to translate it but I'm getting some errors.. this is my code:
Using stream = File.Open(FullUpldPath, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(stream)
Dim result As DataSet = reader.AsDataSet(New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New
ExcelDataTableConfiguration() With {
.UseHeaderRow = True}})
Dim tables As DataTableCollection = result.Tables
End Using
End Using
Dim file__1 as String = "excelpath"
If file__1.EndsWith(".xlsx") Then
' Reading from a binary Excel file (format; *.xlsx)
Dim stream As FileStream = File.Open(file__1, FileMode.Open, FileAccess.Read)
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream)
excelReader.IsFirstRowAsColumnNames = True
dtExcelData = excelReader.AsDataSet()
excelReader.Close()
Return dtExcelData
End If
If file__1.EndsWith(".xls") Then
' Reading from a binary Excel file ('97-2003 format; *.xls)
Dim stream As FileStream = File.Open(file__1, FileMode.Open, FileAccess.Read)
excelReader = ExcelReaderFactory.CreateBinaryReader(stream)
dtExcelData = excelReader.AsDataSet()
excelReader.Close()
Return dtExcelData
End If

Zipping an ExcelPackage in vb.net

I have created an excel document in code and I'm trying to zip the file using ZipArchive. I was attempting to do this by using BinaryReader/Writers but the the stream that I tried to make doesn't seem to contain anything. Any ideas what I'm doing wrong?
Using zip As ZipArchive = New ZipArchive(MemoryStream, ZipArchiveMode.Create, True)
Dim excelFile As ZipArchiveEntry = zip.CreateEntry("QueryExportTest.xlsx")
Using writer As BinaryWriter = New BinaryWriter(excelFile.Open())
Dim excelReader As BinaryReader = New BinaryReader(excel.Stream())
While excelReader.PeekChar() <> -1
writer.Write(excelReader.ReadBoolean)
End While
End Using
End Using
excel was defined earlier with Dim excel As New ExcelPackage()

itextsharp SetFields not setting

I have my temp PDF on the network and am using asp to fill in the fields and then download the file.
The problem I have is that the file downloaded is just the blank template, none of the fields are filled?
My code
Dim doc As New Document(PageSize.A4.Rotate)
Dim ms As New MemoryStream()
Dim writer = PdfWriter.GetInstance(doc, ms)
writer.Open()
Dim PdfR As New PdfReader("http://192.168.0.221/template.pdf")
Dim PdfS As New PdfStamper(PdfR, ms)
Dim fields As AcroFields = PdfS.AcroFields
fields.SetField("s1", "00")
fields.SetField("pono", "100")
PdfS.FormFlattening = True
PdfS.Close()
PdfR.Close()
Dim r = System.Web.HttpContext.Current.Response
r.ContentType = "application/pdf"
r.AddHeader("Content-Disposition", String.Format("attachment;filename=Testing.pdf", "Testing"))
r.BinaryWrite(ms.ToArray)
If anyone else ever hits this issue
1) If you dont mind your fields being editable then remove the FormFlattening command
2) Else add this fields.GenerateAppearances = True

Convert WebControl Image to iText.text.image

This is my code
Dim doc As iTextSharp.text.Document = New iTextSharp.text.Document()
Dim path As String = Request.MapPath("Sample PDFs") & "\Sample.tif"
PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + _
"render\1.pdf", FileMode.Create))
Dim data As clsData = New clsData(GetConnection, enumEgswFetchType.DataTable)
Dim int As Integer = data.GetPageCount(path)
doc.Open()
For ctr As Integer = 0 To int - 1
Dim img As iTextSharp.text.Image
Dim image As New System.Web.UI.WebControls.Image
image.ImageUrl = "ctrls/ViewTif.aspx?path=" + path.ToString + "&page=" + ctr.ToString
img = iTextSharp.text.Image.GetInstance(image, System.Web.UI.WebControls.Image)
doc.Add(image)
Next
doc.Close()
Response.Redirect("~/1.pdf")
Is there any way that I can get the webcontrol image to the itext? the image variable is a dynamic image with a source page returning a jpeg image from a tif file. Or is there any way I can directly put the tif to itext as pdf?
Is there a reason that you need to use System.Web.UI.WebControls.Image? One of the overloads for iTextSharp.text.Image.GetInstance() accepts a URL:
Dim TestFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf")
Using FS As New FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None)
Using Doc As New Document()
Using Writer = PdfWriter.GetInstance(Doc, FS)
Doc.Open()
Doc.Add(New Paragraph("Hello World"))
''//Get the image from a URL
Dim Img = iTextSharp.text.Image.GetInstance("http://www.google.com/images/srpr/logo4w.png")
''//Optionally adjust it
Img.ScaleAbsolute(100, 200)
''//Add it to the document
Doc.Add(Img)
Doc.Close()
End Using
End Using
End Using

asp.net openxml open docx, change content and stream to user

My code is below. I'm trying to open a Word document with Open XML and change certain text. The document must then be send to the client where they can save it on their PC or Open it. It send a document to the client but it is blank. When I save my InMemory document it says the file cannot be open it must contain at least one root element. I'm using Visual STudio 2010 Express. Please help me. What is wrong with my code?
Dim fileName As String = "directory on server\doc.docx"
Dim myDocument As WordprocessingDocument = WordprocessingDocument.Open(fileName, True)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(myDocument.MainDocumentPart.GetStream)
docText = sr.ReadToEnd
sr.Close()
Dim regexText As Regex = New Regex("XXXCourtXXX")
docText = regexText.Replace(docText, "JOHANNESBURG")
Dim ms As New MemoryStream()
Dim sw As StreamWriter = New StreamWriter(ms)
sw.Write(docText)
myDocument.MainDocumentPart.FeedData(ms)
Dim mem = New MemoryStream()
myDocument.MainDocumentPart.GetStream().CopyTo(Response.OutputStream)
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Response.AppendHeader("Content-Disposition", "attachment;filename=Notice.docx")
mem.Position = 0
mem.CopyTo(Response.OutputStream)
Response.Flush()
Response.End()
You're dimming a new memory stream mem, writing nothing to it and then copying it to the output stream. Remove all lines referencing your mem variable.

Resources