iTextSharp generating corrupted PDF in WPF - wpf

I am new to programming with iTextSharp. i have an application that writes in PDF file. File is written in word and than saved in PDF (there are 2 pages). My problem is, that when I want to write on PDF I see the data that was written on but the output PDF is corrupted. I don't understand why PDF gets corrupted?
Public Sub WriteForm(TemplateFilePath As String, NewFilePath As String, data As FormData)
'input output files
Dim oldFile As String = TemplateFilePath
Dim newFile As String = NewFilePath
'if file already exists then delete it
If System.IO.File.Exists(newFile) Then
System.IO.File.Delete(newFile)
End If
' open the reader
Dim reader As New PdfReader(oldFile)
Dim size As Rectangle = reader.GetPageSizeWithRotation(1)
Dim document As New Document(size)
' open the writer
Dim fs As New FileStream(newFile, FileMode.Create, FileAccess.Write)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)
document.Open()
'write data to first page
Me.WriteData(reader, writer, data)
'write second page
Me.AppendCopiedPage(document, writer, reader, 2)
' close the streams
document.Close()
fs.Close()
writer.Close()
reader.Close()
End Sub
'code for WriteData
Private Sub WriteData(reader As PdfReader, writer As PdfWriter, data As FormData)`
Dim cb As PdfContentByte = writer.DirectContent
Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED)
cb.SetColorFill(BaseColor.BLACK)
cb.SetFontAndSize(bf, 10)
' create the first page and add it to the pdf
Dim page1 As PdfImportedPage = writer.GetImportedPage(reader, 1)
cb.AddTemplate(page1, 0, 0)
Me.WriteText(cb, data.SID, 110, 653)
...
End Sub

Related

VB.NET | EMF File becomes plain white in crystal report, How to properly save emf file in sql server

After successfully converted a png file to emf file, another problem begins because when I tried to display the emf file in crystal report it became white.
The emf file was fetched in SQL Server.
I tried to export the data into the database, I found out that the emf file is blank. but I am pretty sure that the emf file I saved is not blank. so the main question is how to properly save an emf file in the database (SQL Server).
here is my code to save the image.
Dim SqlCom As SqlCommand
Dim imageData As Byte()
Dim sFileName As String
Dim qry As String
Try
If jonsqlcon.State = ConnectionState.Closed Then
jonsqlcon.Open()
End If
imageData = ReadFile(sFilePath)
sFileName = System.IO.Path.GetFileName(sFilePath)
qry = "INSERT INTO Signature (ControlNo,Sig) " & _
"VALUES(#ControlNo,#Sig)"
SqlCom = New SqlCommand(qry, jonsqlcon)
SqlCom.Parameters.Add(New SqlParameter("#ControlNo", TxtControlNo.Text))
SqlCom.Parameters.Add(New SqlParameter("#Sig", DirectCast(imageData, Object)))
SqlCom.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
and here is the ReadFile Function
Private Function ReadFile(ByVal sPath As String) As Byte()
Dim data As Byte() = Nothing
Dim fInfo As New FileInfo(sPath)
Dim numBytes As Long = fInfo.Length
Dim fStream As New FileStream(sPath, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fStream)
data = br.ReadBytes(CInt(numBytes))
Return data
End Function

Convert From Byte[] to File

I use the following Function to convert a file to Byte()
Public Function FileToByteArray(ByVal _FileName As String) As Byte()
Dim _Buffer() As Byte = Nothing
Try
' Open file for reading
Dim _FileStream As New System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
' attach filestream to binary reader
Dim _BinaryReader As New System.IO.BinaryReader(_FileStream)
' get total byte length of the file
Dim _TotalBytes As Long = New System.IO.FileInfo(_FileName).Length
' read entire file into buffer
_Buffer = _BinaryReader.ReadBytes(CInt(Fix(_TotalBytes)))
' close file reader
_FileStream.Close()
_FileStream.Dispose()
_BinaryReader.Close()
Catch _Exception As Exception
' Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
End Try
Return _Buffer
End Function
I save the file ("C:\sample.xlsx") using this function to database(I use Microsoft SQL Server) as SqlDbType.Image
Below is the code that I use to get the value from db and try to convert it as a file again.
Dim FileInBinary() As Byte
Dim CurrentRS As Recordset
'Select
SQLString = "SELECT FileInBinary from table where ID=1"
'Get value to a recordSet
CurrentRS = ServerRunSQL_Return(SQLString)
'SaveValue to Dim
FileInBinary = CurrentRS.Fields(0).Value
'Try to convert
My.Computer.FileSystem.WriteAllBytes("C:\sample_new.xlsx", FileInBinary, True)
I also tried:
File.WriteAllBytes("C:\sample_new.xlsx", FileInBinary)
How can I select this value and convert it again as file ("C:\sample_new.xlsx")?
Replace the Function FileToByteArray with File.ReadAllBytes("C:\sample.xlsx")
Below is the code to get the value from db and convert it as a file again.
Dim FileInbinary As Byte()
SqlConn.Open()
Dim command As New SqlCommand("SELECT FileInBinary from table where ID=1", SqlConn)
FileInbinary = DirectCast(command.ExecuteScalar(), Byte())
SqlConn.Close()
File.WriteAllBytes("C:\sample_new.xlsx", FileInbinary)

How do I pull a .pdf from a database, then insert it into email as an attachment without writing it to the file structure [duplicate]

This question already has answers here:
Attach a file from MemoryStream to a MailMessage in C#
(8 answers)
Closed 5 years ago.
I'm migrating web servers and rewriting some of our applications (vb.net environment). In doing so, I have come across a dilema, and would greatly appreciate some help.
I can successfully pull a .pdf file out of a database and display it:
Dim iID As Integer
Dim bPDF As Byte()
iID = Convert.ToInt32(Request.QueryString("Id"))
bPDF = CodeMod.GetPdfBytes(iID)
Response.ContentType = "application/pdf"
Response.OutputStream.Write(bPDF, 0, bPDF.Length)
---------------------------------
Public Function GetPdfBytes(ByVal id As Int32) As Byte()
Dim SQLcon As New SqlClient.SqlConnection
Dim SQLcmd As New SqlClient.SqlCommand
Dim dt As New DataTable
SQLcon.ConnectionString = sConnection("pdfStore")
SQLcmd.CommandText = "[DOIMSQL,1433].[DOI_PDF_Storage].dbo.sel_pdf_id"
SQLcmd.CommandType = CommandType.StoredProcedure
SQLcmd.Parameters.Add("#pdf_id", SqlDbType.VarChar).Value = id
SQLcmd.Connection = SQLcon
SQLcon.Open()
dt.Load(SQLcmd.ExecuteReader)
SQLcon.Close()
GetPdfBytes = DirectCast(dt.Rows(0)("pdf_file"), Byte())
End Function
AND I can successfully send an email with a file attachment:
CodeMod.sendMail(strTo, strFrom, "Test Email", "Test Content",, Server.MapPath("/Test/TEST.pdf"))
---------------------------------
Public Sub sendMail(strTo As String, strFrom As String, strSubject As String, strMsg As String, Optional ByVal strCc As String = "", Optional ByVal file As String = "")
Dim oMMsg As New Net.Mail.MailMessage()
oMMsg.From = New MailAddress(strFrom)
oMMsg.To.Add(strTo)
oMMsg.Subject = strSubject
oMMsg.Body = strMsg
oMMsg.IsBodyHtml = True
If file <> "" Then oMMsg.Attachments.Add(New Attachment(file))
Dim client As New SmtpClient()
client.Host = "correct.information"
client.Port = 25
client.Send(oMMsg)
End Sub
What I need to do is to marry these two capabilities. I need to retrieve a .pdf from out of the database and send it as an email attachment...
...without ever writing the file to the file structure.
If I get it right, you can write that PDF into a memory stream and make an attachment directly from the memory stream. There is an existing separate question on how to attach from memory stream
Attach a file from MemoryStream to a MailMessage in C#

Read binary file from database but don't save it

I wrote a windows form program in VB
In the from of my Project I want if a button is clicked, show a file (pdf or word) that save in database. I use this code for doing it and this code works fine. but files are copied in my bin folder of project. I want that these files only show on screen but not saved anywhere. Can anyone help me?
Try
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim size As Integer = 1024 * 1024
Dim buffer As Byte() = New Byte(size - 1) {}
Dim readBytes As Integer = 0
Dim index As Integer = 0
filename = dr("DocName")
Using fs As New FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None)
While (InlineAssignHelper(readBytes, CInt(dr.GetBytes(0, index, buffer, 0, size)))) > 0
fs.Write(buffer, 0, readBytes)
index += readBytes
End While
End Using
End While
End Using
Catch ex As Exception
Dim errMessageBox As New Puzzle.ErrorHandler
errMessageBox.ShowError("Err", "FrmCustomer:DbTools_GetAttachFile", "line", ex.Message)
Exit Sub
Finally
ConImage.Close()
End Try
End Using
Dim prc As New Process()
prc.StartInfo.FileName = filename
prc.Start()
Just modify the following line, and it should work.
'filename = dr("DocName") ' replace this line
filename = IO.Path.GetTempFileName ' with this
Basically, IO.Path.GetTempFileName will get a temporary filename in the Windows Temp folder. This folder is used for keeping temporary files and is usually cleaned by various disk cleaning tools automatically or when you ask windows to reclaim wasted space (via Disk Cleanup program).
Note that you would need the same filename when opening the file.

Unzip a zip file in silverlight

I am trying to develop code to unzip file from the zip file in Silverlight 5. The files are in a directory within the zip file.
I translated this code I found elsewhere from c# to VB since we are a VB shop. It is failing on the fourth line "Object reference not set to an instance of an object.".
I realize now that the problem is that the third line is expecting a relative uri and I am passing it a file, but I don't know how to fix this.
Can you tell me what is wrong with this code. I will also welcome other ideas.
Thanks.
Public Shared Function GetZipContents(ByVal filename As String) As String()
Try
Dim zipStream As System.IO.Stream = New System.IO.MemoryStream()
Dim zipInfo As New StreamResourceInfo(zipStream, Nothing)
Dim streamInfo As StreamResourceInfo = Application.GetResourceStream(zipInfo, New Uri(filename, UriKind.Relative))
Dim fileStream As Stream = streamInfo.Stream
Dim names As New List(Of String)()
Dim reader As New BinaryReader(fileStream)
Do While reader.ReadUInt32() = &H4034B50
' Skip the portions of the header we don't care about
reader.BaseStream.Seek(14, SeekOrigin.Current)
Dim compressedSize As UInteger = reader.ReadUInt32()
Dim uncompressedSize As UInteger = reader.ReadUInt32()
Dim nameLength As Integer = reader.ReadUInt16()
Dim extraLength As Integer = reader.ReadUInt16()
Dim nameBytes() As Byte = reader.ReadBytes(nameLength)
names.Add(Encoding.UTF8.GetString(nameBytes, 0, nameLength))
reader.BaseStream.Seek(extraLength + compressedSize, SeekOrigin.Current)
Loop
' Move the stream back to the begining
fileStream.Seek(0, SeekOrigin.Begin)
Return names.ToArray()
Catch ex As Exception
MessageBox.Show(ex.Message)
Return Nothing
End Try
End Function
There is quick and dirty way to unzip in Silverlight.
Use Application.GetResourceStream Method.
http://msdn.microsoft.com/en-us/library/cc190632(v=vs.95).aspx
Check out my blogpost on this: http://www.sharpgis.net/post/2010/08/25/REALLY-small-unzip-utility-for-Silverlight-e28093-Part-2.aspx
Sorry I would have time to explore the suggestions. I did find a way to accomplish my goal on my own. See the code below. I would be using this code either because the Technical Leader here prefers I do it a different way using a WCF service. Warning I was not able to test this code 100% since I am not planning to use it, but it is close to being right.
Imports ICSharpCode.SharpZipLib.Zip
Public Shared Sub UnZip(ByVal SrcFile As String, ByVal DstFile As String, ByVal BufferSize As Integer)
Try
Dim _FileName As String
Dim _ZipEntry As ZipEntry
Dim _FileStreamOut As FileStream = Nothing
Dim _Done As Boolean = False
Dim _FileStreamIn As New FileStream(SrcFile, FileMode.Open, FileAccess.Read)
Dim _ZipInStream As New ZipInputStream(_FileStreamIn)
Do Until _Done = True
_ZipEntry = _ZipInStream.GetNextEntry()
If IsNothing(_ZipEntry) Then
_Done = True
Exit Do
End If
_FileName = DstFile & "\" & _ZipEntry.Name
_FileName = _FileName.Replace("/", "\")
If Right(_FileName, 1) = "\" Then
If Directory.Exists(_FileName) = False Then
Directory.CreateDirectory(_FileName)
End If
Else
_FileStreamOut = New FileStream(_FileName, FileMode.Create, FileAccess.Write)
Dim size As Integer
Dim buffer(BufferSize - 1) As Byte
Do
size = _ZipInStream.Read(buffer, 0, buffer.Length)
_FileStreamOut.Write(buffer, 0, size)
Loop While size > 0
End If
Loop
_ZipInStream.Close()
_FileStreamOut.Close()
_FileStreamIn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Resources