Implementing an Image Download in VB.NET - asp.net

I am trying to implement an image download in vb.net where the client clicks a button and the browser downloads an image for the client from a file in the server.
I tried this:
Private Sub DownloadImage(ByVal ImageURL As String)
Dim Buffer(6000000) As Byte
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=" & ImageURL & ".jpg")
Response.ContentType = "image/jpeg"
Response.BinaryWrite(Buffer)
Response.Flush()
Response.End()
End Sub
But this has 2 problems. First, it doesn't actually show up the image when I download it so it doesn't work properly. Secondly I have to manually enter the size of the image to determine the size of the byte array.
Please help me out, I couldn't find any resources on internet and couldn't get my head around it.
Thanks!

This is a sample image handler I've used for several years. It's probably got some room for improvement, but it is intended to be used as the src attribute for an img tag.
<img src="Thumbs.ashx?img=/ImagePath/BigImage.jpg&max=100" />
It's a direct copy-paste of my working code and it's got some references to private code - but it should give you a good start. It will create a thumbnail image so it doesn't have to be regenerated each time, if the thumbnail has already been generated. Hope this helps...
<%# WebHandler Language="VB" Class="GetImage" %>
Imports Web.Utilities
Imports Common
Imports System
Imports System.Drawing
Imports System.Web
Imports System.IO
''' <summary>
''' Resizes the image supplied in the "img" querystring parameter and writes it to the OutputStream in jpg format.
''' The default dimension is a max of 90 pixels (H or W; whichever is larger).
''' The "max" querystring parameter can alter the maximum dimension by supplying a new dimension as an integer.
''' If the file name contains an ampersand, it should be replaced with [amp].
''' </summary>
''' <remarks></remarks>
Public Class GetImage : Implements IHttpHandler
Private thumbFolder As String = "/images/Thumbs/"
Private trapCount As Integer = 0
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'General.PreventClientCaching()
'context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim maxSize As Integer = 90
Dim img As String = context.Request.QueryString("img")
Dim strMax As String = context.Request.QueryString("max")
If Not strMax.IsNullOrEmpty AndAlso IsNumeric(strMax) Then
maxSize = CInt(strMax)
End If
If maxSize > 1000 Then
maxSize = 1000
End If
If img.IsNullOrEmpty Then
img = "/images/PicUnavailable.jpg"
End If
Try
Dim uri As New System.Uri(img, UriKind.RelativeOrAbsolute)
img = uri.AbsolutePath
Catch ex As Exception
End Try
General.SetContentType(General.FileType.Jpg)
img = img.Replace("[amp]", "&")
ServeImage(context, img, maxSize)
End Sub
Private Sub ServeImage(ByVal context As HttpContext, ByVal imagePath As String, ByVal maximumSize As Integer)
Dim imgFile As Image = Nothing
Dim existingThumb As String = imagePath.Replace("/", "{s}") & "_" & maximumSize.ToString & ".jpg"
Dim doPurge As Boolean
Boolean.TryParse(context.Request.QueryString("purge"), doPurge)
' Check to see if the thumbnail has already been generated and it's older than the source.
' If it is, delete it.
If File.Exists(context.Server.MapPath(thumbFolder & existingThumb)) Then
If doPurge Then
File.Delete(context.Server.MapPath(thumbFolder & existingThumb))
Else
If File.GetLastWriteTime(context.Server.MapPath(thumbFolder & existingThumb)) < File.GetLastWriteTime(context.Server.MapPath(imagePath)) Then
Try
File.Delete(context.Server.MapPath(thumbFolder & existingThumb))
Catch ex As Exception
End Try
End If
End If
End If
' If the thumbnail already exists, write the byte array to the output stream
If File.Exists(context.Server.MapPath(thumbFolder & existingThumb)) Then
Dim fs As FileStream = Nothing
Try
fs = New FileStream(context.Server.MapPath(thumbFolder & existingThumb), IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim imgLen As Long = fs.Length()
Dim imgData(imgLen) As Byte
fs.Read(imgData, 0, Integer.Parse(imgLen.ToString()))
context.Response.OutputStream.Write(imgData, 0, Integer.Parse(imgLen.ToString()))
Catch ex2 As UnauthorizedAccessException
'context.Server.Transfer(img)
Throw
Catch exIO As IOException
'context.Server.Transfer(img)
Throw
Finally
If Not fs Is Nothing Then
fs.Dispose()
fs = Nothing
End If
End Try
' the file doesn't exist, so render it to the output stream and save it to the thumbnail
Else
Try
imgFile = Image.FromFile(context.Server.MapPath(imagePath))
Dim maxDim As Integer = maximumSize
Dim maxH As Integer = maximumSize
Dim maxW As Integer = maximumSize
'If img.Height > maxH OrElse img.Width > maxW Then
Dim thumb As Image
Dim gfx As Graphics
Dim rect As Rectangle
If imgFile.Height >= imgFile.Width Then 'portrait or square
Dim newW As Integer
newW = CInt((maxH / imgFile.Height) * imgFile.Width)
thumb = New Bitmap(newW, maxDim)
gfx = Graphics.FromImage(thumb)
gfx.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
gfx.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
gfx.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
rect = New Rectangle(0, 0, newW, maxDim)
Else 'landscape
Dim newH As Integer
newH = CInt((maxW / imgFile.Width) * imgFile.Height)
thumb = New Bitmap(maxDim, newH)
gfx = Graphics.FromImage(thumb)
gfx.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
gfx.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
gfx.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
rect = New Rectangle(0, 0, maxDim, newH)
End If
gfx.DrawImage(imgFile, rect)
thumb.Save(context.Response.OutputStream, Drawing.Imaging.ImageFormat.Jpeg)
thumb.Save(context.Server.MapPath(thumbFolder & existingThumb), Drawing.Imaging.ImageFormat.Jpeg)
gfx.Dispose()
thumb.Dispose()
gfx = Nothing
thumb = Nothing
Catch ex As Exception
Dim fs As FileStream = Nothing
Try
fs = New FileStream(context.Server.MapPath(imagePath), IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim imgLen As Long = fs.Length()
Dim imgData(imgLen) As Byte
fs.Read(imgData, 0, Integer.Parse(imgLen.ToString()))
context.Response.OutputStream.Write(imgData, 0, Integer.Parse(imgLen.ToString()))
Catch ex2 As UnauthorizedAccessException
'context.Server.Transfer(img)
Throw
Catch exIO As IOException
'context.Server.Transfer(img)
If trapCount > 0 Then
Throw
End If
trapCount += 1
ServeImage(context, "/images/PicUnavailable.jpg", maximumSize)
Finally
If Not fs Is Nothing Then
fs.Dispose()
fs = Nothing
End If
End Try
Finally
If Not imgFile Is Nothing Then
imgFile.Dispose()
imgFile = Nothing
End If
End Try
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Related

Converting HTML to PDF and attaching to email .NET

I am looking to use PDFSharp to convert a HTML page into a PDF. This then is attached into an email and sent all in one go.
So, I have a aspx page and vb code file in which gets called through a database SQL job.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim ReqUrl As String, WorkflowID As String = String.Empty
Using con As New SqlConnection(GlobalVariables.ConStr)
Using com As New SqlCommand("EXEC App.GetWorkflowToSend", con)
con.Open()
Using dr = com.ExecuteReader
Try
While dr.Read
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
ReqUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + dr.Item("WorkflowLink")
WorkflowID = dr.Item("WorkflowID")
Dim r As String = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + dr.Item("WorkflowLink")
Dim p As String = Server.MapPath("~\Data\Files") + "\" + WorkflowID + ".pdf"
Dim t As Thread = New Thread(CType(
Function()
ConvertHTML(r, p)
SendMail(Nothing, EmailFrom, "email#address", "New PDF Generated " + WorkflowID, r + "<br/>" + p + "<br/>" + WorkflowID, EmailUser, EmailPass, EmailHost, EmailPort, EmailSSL, "", Nothing, p)
End Function, ThreadStart))
t.SetApartmentState(ApartmentState.STA)
t.Start()
Response.Write(r + "<br>")
Response.Write(p)
End While
Catch
SendMail(Nothing, EmailFrom, "email#address", "Error: " + Err.Description, WorkflowID, EmailUser, EmailPass, EmailHost, EmailPort, EmailSSL, "", Nothing)
End Try
End Using
End Using
End Using
End Sub
In the vb code I essentially call a database stored procedure. This returns some records.
For each of these records, I am currently using HttpContext.Current.Request.Url to make up a string which is essentially the the document url.
I also then declare and specify the location as a String of where I want the converted PDF to be stored.
Public Shared Function ConvertHTML(HTMLPage As String, FileName As String) As String
Dim pngfilename As String = Path.GetTempFileName()
Dim res As String = "" ' = ok
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
'Try
Using wb As System.Windows.Forms.WebBrowser = New System.Windows.Forms.WebBrowser
wb.ScrollBarsEnabled = False
wb.ScriptErrorsSuppressed = True
wb.Navigate(HTMLPage)
While Not (wb.ReadyState = WebBrowserReadyState.Complete)
Application.DoEvents()
End While
wb.Width = wb.Document.Body.ScrollRectangle.Width
wb.Height = wb.Document.Body.ScrollRectangle.Height
If wb.Height > 3000 Then
wb.Height = 3000
End If
' Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
Dim b As Bitmap = New System.Drawing.Bitmap(wb.Width, wb.Height)
Dim hr As Integer = b.HorizontalResolution
Dim vr As Integer = b.VerticalResolution
wb.DrawToBitmap(b, New Rectangle(0, 0, wb.Width, wb.Height))
wb.Dispose()
If File.Exists(pngfilename) Then
File.Delete(pngfilename)
End If
b.Save(pngfilename, Imaging.ImageFormat.Png)
b.Dispose()
Using doc As PdfSharp.Pdf.PdfDocument = New PdfSharp.Pdf.PdfDocument
Dim page As PdfSharp.Pdf.PdfPage = New PdfSharp.Pdf.PdfPage()
page.Width = PdfSharp.Drawing.XUnit.FromInch(wb.Width / hr)
page.Height = PdfSharp.Drawing.XUnit.FromInch(wb.Height / vr)
doc.Pages.Add(page)
Dim xgr As PdfSharp.Drawing.XGraphics = PdfSharp.Drawing.XGraphics.FromPdfPage(page)
Dim img As PdfSharp.Drawing.XImage = PdfSharp.Drawing.XImage.FromFile(pngfilename)
xgr.DrawImage(img, 0, 0)
doc.Save(FileName)
doc.Close()
img.Dispose()
xgr.Dispose()
End Using
End Using
Return res
End Function
I run the conversion function with these two strings and finally call a mailing function.
PDF Error
The problem I am having at the moment is the attached PDF I receive in the email doesn't contain the correct output and states 'Navigation to the webpage was cancelled'.
http://127.0.0.1/PDF/TTR/4
C:\inetpub\wwwroot\Prod\Data\Files\4.pdf
I also sent the two strings as output within the email and they look ok.
I'm sure there is something small missing whether that be in my conversion function or just in the main code file.

HTTP/2 Image load times - waiting for the last one to finish

This is baffling me. On a new server (Windows Server 2016) my images seem to be loading in synchronously. The browser is attempting to download them all at the same time, but something is stopping the image from loading until the previous one has finished. The time to first byte increases as each image is attempted to be loaded.
EDIT: I have posted my imagehandler code below, but you can see the problem exists when loading .jpg in its native format (see screenshot about half way down).
EDIT 2: I have disabled http/2 and added a screenshot.
My SVG image handler code (problem exists with image.ashx also):
Dim freshness As TimeSpan = New TimeSpan(1, 0, 0, 0)
Dim now As DateTime = DateTime.Now
Response.Cache.SetExpires(now.Add(freshness))
Response.Cache.SetMaxAge(freshness)
Response.Cache.SetCacheability(HttpCacheability.Public)
Response.Cache.SetValidUntilExpires(True)
Response.Cache.VaryByParams("colour") = True
Response.Cache.VaryByParams("colour2") = True
Response.Cache.VaryByParams("svg") = True
Response.Cache.VaryByParams("rnd") = True
Response.Cache.VaryByHeaders("rnd") = True
Response.Cache.VaryByHeaders("Type") = True
Dim sSVG As String = Request.QueryString("svg").Split("-")(0)
If sSVG = String.Empty Then
Try
sSVG = Request.ServerVariables("SCRIPT_NAME").Split("-")(0)
Catch ex As Exception
sSVG = "svg"
End Try
End If
Dim xDoc As XDocument = XDocument.Load(Server.MapPath("\images\icons\svg\" & sSVG & ".svg"))
Dim sColour As String = "FFFFFF"
Dim sColour2 As String = "FFFFFF"
Dim sXML As String = xDoc.Document.ToString
If Request.QueryString("Colour") <> String.Empty Then
sColour = Request.QueryString("Colour")
Else
Try
sColour = sSVG.Split("-")(1)
Catch ex As Exception
End Try
End If
If Request.QueryString("Colour2") <> String.Empty Then
sColour2 = Request.QueryString("Colour2")
Else
Try
sColour = sSVG.Split("-")(2)
Catch ex As Exception
End Try
End If
sXML = sXML.Replace("COLOUR2", sColour2)
sXML = sXML.Replace("COLOUR", sColour)
Response.Headers.Add("Vary", "Accept-Encoding")
Response.ContentType = "image/svg+xml"
Response.Write(sXML)
HTTP/2 disabled:

VB.NET FTP File Download

I'm trying to set up my program to connect to my FTP and download files directly from my server. This what I have so far. I don't know what I'm doing wrong, or where I'm going wrong, because no matter how I code it either says "End Expected" or "Method can't handle etc due to signatures not being compatible"
I don't know what I'm doing wrong, any help would be greatly appreciated.
Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
(ByVal downloadpath As String, ByVal ftpuri As String, ByVal ftpusername As String, ByVal ftppassword As String)
'Create a WebClient.
Dim request As New WebClient()
' Confirm the Network credentials based on the user name and password passed in.
request.Credentials = New Net.NetworkCredential("Username", "Password")
'Read the file data into a Byte array
Dim bytes() As Byte = request.DownloadData("ftp://ftp.yourwebsitename/file.extension")
Try
' Create a FileStream to read the file into
Dim DownloadStream As FileStream = IO.File.Create("C:\Local\Test.zip")
' Stream this data into the file
DownloadStream.Write(bytes, 0, bytes.Length)
' Close the FileStream
DownloadStream.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
MessageBox.Show("Process Complete")
End Sub
You probably pasted an existing method inside a Button.Click handler by mistake.
Rebuilding what was probably the original method is almost enough.
Note that this FTP procedure is a quite basic. You can rely on it only when downloading from a known remote resource. Also, as it it, it doesn't allow to show the download progress or even to cancel it.
Maybe take a look at the WebClient.DownloadDataAsync method, which allows to easily implement a progress bar and cancel the download procedure, when needed.
Also, if you're interested, in this SO question, you can find some notes and a sample Form, which can be included in a Project, to test some features of the FtpWebRequest.
Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
Button16.Enabled = False
DownloadFile("C:\Local\Test.zip", "ftp://ftp.example.com/file.ext", "[username]", "[password]")
Button16.Enabled = True
End Sub
Private Sub DownloadFile(destinationPath As String, ftpResource As String, ftpUsername As String, ftpPassword As String)
Dim client As New WebClient()
client.Credentials = New NetworkCredential(ftpUsername, ftpPassword)
Try
Dim dataBytes() As Byte = client.DownloadData(ftpResource)
If dataBytes.Length > 0 Then
File.WriteAllBytes(destinationPath, dataBytes)
MessageBox.Show("Download Complete")
Else
MessageBox.Show("Download failed")
End If
Catch ex As WebException
MessageBox.Show(ex.Message)
Catch ex As IoException
MessageBox.Show(ex.Message)
End Try
End Sub
Here is a Console solution. Compile this into a exe file, and run it by double-clicking the executable or get a scheduler (i.e., Windos Task Scheduler) to open and run the file (it runs as soon as it opens).
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Linq
Imports System.Text
Imports System.Net
Imports System.IO
Namespace ConsoleApplication1
Class Program
Private Shared Sub Main(ParamArray ByVal args() As String)
If args.Any Then
' Do code that references args
Dim dt As DateTime = DateTime.Today.AddDays(-1)
Dim date As String = String.Format("{0:yyyyMMdd}", dt)
Dim p As Program = New Program
p.getFTPFile(("raw_CA_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_EM_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_GLB_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_US_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
Else
' Do code that depends on no input arguments.
Dim dt As DateTime = DateTime.Today.AddDays(-1)
Dim date As String = String.Format("{0:yyyyMMdd}", dt)
Dim p As Program = New Program
p.getFTPFile(("raw_CA_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_EM_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_GLB_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_US_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
End If
End Sub
Private Sub getFTPFile(ByVal FTPFile As String)
FTPSettings.IP = "000.000.100.000"
FTPSettings.UserID = "your_id"
FTPSettings.Password = "your_password"
Dim reqFTP As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
Try
Dim outputStream As FileStream = New FileStream(("C:\Downloads\AFL_Files\" + FTPFile), FileMode.Create)
reqFTP = CType(FtpWebRequest.Create(("ftp://something#ftp.corp.com/your_path/" + FTPFile)),FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = true
reqFTP.Credentials = New NetworkCredential(FTPSettings.UserID, FTPSettings.Password)
Dim response As FtpWebResponse = CType(reqFTP.GetResponse,FtpWebResponse)
ftpStream = response.GetResponseStream
Dim cl As Long = response.ContentLength
Dim bufferSize As Integer = 2048
Dim readCount As Integer
Dim buffer() As Byte = New Byte((bufferSize) - 1) {}
readCount = ftpStream.Read(buffer, 0, bufferSize)
While (readCount > 0)
outputStream.Write(buffer, 0, readCount)
readCount = ftpStream.Read(buffer, 0, bufferSize)
End While
ftpStream.Close
outputStream.Close
response.Close
Catch ex As Exception
If (Not (ftpStream) Is Nothing) Then
ftpStream.Close
ftpStream.Dispose
End If
Throw New Exception(ex.Message.ToString)
End Try
End Sub
Public Class FTPSettings
Public Shared Property IP As String
Get
End Get
Set
End Set
End Property
Public Shared Property UserID As String
Get
End Get
Set
End Set
End Property
Public Shared Property Password As String
Get
End Get
Set
End Set
End Property
End Class
End Class
End Namespace

vb.net code that will export / convert multiple selected files in to one pdf file

I am trying to create a code that will convert multiple selected files to one pdf file . Currently the code exports the selected files in to a zip file. But I want to open all the selected files in one single pdf file .
For your assistance I am providing the code that exports all files into one zip file.
In the code below there are two table mentioned. one is document and another is vacancyapplication. In the document table all the files are stored guid is the unique id in the document table.
Imports System
Imports System.Web
Imports System.IO
Imports System.Collections.Generic
Imports Ionic.Zip
Imports System.Linq
Imports NLog
Public Class download_bulk_cv : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim _logger As Logger = LogManager.GetCurrentClassLogger()
Dim vacancy = New Vacancy(context.Request("v"))
context.Response.Clear()
context.Response.ContentType ="application/zip"
context.Response.AddHeader("content-disposition", "attachment; filename=" & vacancy.Title.Replace(" ", "_") & "_" & Now.ToString("yyyy-MMM-dd-HHmmss") & ".zip")
Dim files = New List(Of String)()
For Each docPath As String In From row As DataRow In DB.GetData("select guid, originalfilename from document where id in (select candidatecvid from vacancyapplication where id in (" & context.Request("a").ToString() & "))").Rows Let guid = row.Item("guid").ToString() Select HttpContext.Current.Server.MapPath("~/documents") & "\" & Left(guid, 1) & "\" & Right(guid, 1) & "\" & guid & "." & System.IO.Path.GetExtension(row.Item("originalfilename")).ToLower().Substring(1)
If File.Exists(docPath) Then
files.Add(docPath)
'_logger.Info(docPath)
End If
Next
Using zip As New ZipFile()
zip.AddFiles(files.ToArray(), "CVs") '.AddFile(docPath, "CVs")
zip.AddEntry("info.txt", files.Count.ToString.ToString() & "CVs archived", Encoding.Default)
zip.Save(context.Response.OutputStream)
End Using
context.Response.End()
End Sub
End Class
i have written the following code to merge the pdf documents but its not working
Edited code
Public Class preview_bulk_cv : Implements IHttpHandler
''Implements IDisposable
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim _logger As Logger = LogManager.GetCurrentClassLogger()
Dim vacancy = New Vacancy(context.Request("v"))
Dim files = New List(Of String)()
Dim sourceFiles = New List(Of String)()
Dim directorypath As String = HttpContext.Current.Server.MapPath("~/documents") & "\download\" & Now.ToString("yyyy-MMM-dd") & "\" & vacancy.Title.Replace(" ", "_") & "\"
Dim pdf_document As iTextSharp.text.Document = Nothing
Dim pdf_copier As iTextSharp.text.pdf.PdfCopy = Nothing
context.Response.Clear()
context.Response.ContentType = "application/pdf"
context.Response.AddHeader("content-disposition", "attachment; filename=" & vacancy.Title.Replace(" ", "_") & "_" & Now.ToString("yyyy-MMM-dd-HHmmss") & ".pdf")
For Each docPath As String In From row As DataRow In DB.GetData("select guid, originalfilename from document where id in (select candidatecvid from vacancyapplication where id in (" & context.Request("a").ToString() & "))").Rows Let guid = row.Item("guid").ToString() Select HttpContext.Current.Server.MapPath("~/documents") & "\" & Left(guid, 1) & "\" & Right(guid, 1) & "\" & guid & "." & System.IO.Path.GetExtension(row.Item("originalfilename")).ToLower().Substring(1)
Dim epath As String = HttpContext.Current.Server.MapPath("~/documents") & "\download\" & Now.ToString("yyyy-MMM-dd") & "\" & vacancy.Title.Replace(" ", "_") & "\" & Now.ToString("yyyy-MMM-dd-HHmmss") & ".pdf"
Converter.ConvertDocument(docPath, epath)
If File.Exists(epath) Then
sourceFiles.Add(epath)
End If
If File.Exists(docPath) Then
files.Add(docPath)
'_logger.Info(docPath)
End If
Next
Dim all_source_files As String() = sourceFiles.ToArray()
Dim docs As PdfDocument() = New PdfDocument(all_source_files.Length - 1) {}
For i As Integer = 0 To all_source_files.Length - 1
Dim reader As New PdfReader(all_source_files(i))
' Using reader As New iTextSharp.text.pdf.PdfReader(all_source_files(i))
Dim finalpdf As String = HttpContext.Current.Server.MapPath("~/documents") & "\download\" & Now.ToString("yyyy-MMM-dd") & "\" & vacancy.Title.Replace(" ", "_") & "\finalcv.pdf"
If i = 0 Then
pdf_document = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1))
pdf_copier = New iTextSharp.text.pdf.PdfCopy(pdf_document, New IO.FileStream(finalpdf, IO.FileMode.Create))
pdf_document.Open()
End If
For page_num As Integer = 1 To reader.NumberOfPages
pdf_copier.AddPage(pdf_copier.GetImportedPage(reader, page_num))
Next
' End Using
Next
pdf_copier.Close()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
I am new with vb.net . I appreciate your kind assistance.
This is an example of code to combine an array of PDFs into 1 merged PDF, it requires a reference to the iTextSharp dll I mentioned in my comment. If you can save each file individually to a PDF now, you can use something like System.IO.Directory.GetFiles(your_directory) to get the array of file names and then combine them with something like the code here:
' This requires a reference to the iTextSharp library (http://sourceforge.net/projects/itextsharp/)
Dim pdfs() As String ' all of your PDF files you'd like to merge
Dim output_pdf As String ' the output file
Dim pdf_document As iTextSharp.text.Document = Nothing
Dim pdf_copier As iTextSharp.text.pdf.PdfCopy = Nothing
For i As Integer = 0 To pdfs.Length - 1
Using pdf_reader As New iTextSharp.text.pdf.PdfReader(pdfs(i))
If i = 0 Then
pdf_document = New iTextSharp.text.Document(pdf_reader.GetPageSizeWithRotation(1))
pdf_copier = New iTextSharp.text.pdf.PdfCopy(pdf_document, New IO.FileStream(output_pdf, IO.FileMode.Create))
pdf_document.Open()
End If
For page_num As Integer = 1 To pdf_reader.NumberOfPages
pdf_copier.AddPage(pdf_copier.GetImportedPage(pdf_reader, page_num))
Next
End Using
Next
pdf_copier.Close()
Here is the code for converting any documents to pdf files and merging them into one single pdf file
<%# WebHandler Language="VB" Class="PDFMerge" %>
Imports System
Imports System.Web
Imports System.IO
Imports System.Collections.Generic
Imports Ionic.Zip
Imports System.Linq
Imports NLog
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.Text.RegularExpressions
Public Class PDFMerge : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim _logger As Logger = LogManager.GetCurrentClassLogger()
Dim vacancy = New Vacancy(context.Request("v"))
Dim sourceFiles = New List(Of String)()
For Each docPath As String In From row As DataRow In DB.GetData("database query").Rows Select HttpContext.Current.Server.MapPath("~/Downloads") & "\" System.IO.Path.GetExtension(row.Item("originalfilename")).ToLower().Substring(1)
Dim epath As String = HttpContext.Current.Server.MapPath("~/Downloads") & "\" & Now.ToString("yyyy-MMM-dd") & "\" & vacancy.Title.Replace(" ", "_") & "\" & Now.ToString("yyyy-MMM-dd-HHmmss") & ".pdf"
Converter.ConvertDocument(docPath, epath)
If File.Exists(epath) Then
sourceFiles.Add(epath)
End If
Next
Dim OutputFileName As String = HttpContext.Current.Server.MapPath("~/Downloads") & "\" & Now.ToString("yyyy-MMM-dd") & "\" & vacancy.Title.Replace(" ", "_") & "\" & vacancy.Title.Replace(" ", "_") & ".pdf"
PDFMerge.MergeFiles(OutputFileName, sourceFiles.ToArray)
Dim mPDFFile As FileStream = File.OpenRead(OutputFileName)
Dim mPDFFileBuffer(mPDFFile.Length - 1) As Byte
mPDFFile.Read(mPDFFileBuffer, 0, mPDFFileBuffer.Length)
mPDFFile.Close()
System.Diagnostics.Process.Start(OutputFileName)
context.Response.Clear()
context.Response.ContentType = "application/pdf"
context.Response.AddHeader("Content-Disposition", "attachment;filename=" & OutputFileName)
context.Response.AddHeader("Content-Length", mPDFFileBuffer.Length)
context.Response.OutputStream.Write(mPDFFileBuffer, 0, mPDFFileBuffer.Length)
mPDFFileBuffer = Nothing
context.Response.Flush()
context.Response.End()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Public Shared Sub MergeFiles(destinationFile As String, sourceFiles As String())
Try
Dim f As Integer = 0
Dim reader As New PdfReader(sourceFiles(f)) ' we create a reader for a certain document
Dim n As Integer = reader.NumberOfPages ' we retrieve the total number of pages
'Console.WriteLine("There are " + n + " pages in the original file.");
Dim document As New Document(reader.GetPageSizeWithRotation(1)) ' step 1: creation of a document-object
Dim writer As PdfWriter = PdfWriter.GetInstance(document, New FileStream(destinationFile, FileMode.Create)) ' step 2: we create a writer that listens to the document
document.Open() ' step 3: we open the document
Dim cb As PdfContentByte = writer.DirectContent
Dim page As PdfImportedPage
Dim rotation As Integer
' step 4: we add content
While f < sourceFiles.Length
Dim i As Integer = 0
While i < n
i += 1
document.SetPageSize(reader.GetPageSizeWithRotation(i))
document.NewPage()
page = writer.GetImportedPage(reader, i)
rotation = reader.GetPageRotation(i)
If rotation = 90 OrElse rotation = 270 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, _
reader.GetPageSizeWithRotation(i).Height)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, _
0)
'Console.WriteLine("Processed page " + i);
End If
End While
f += 1
If f < sourceFiles.Length Then
reader = New PdfReader(sourceFiles(f))
' we retrieve the total number of pages
'Console.WriteLine("There are " + n + " pages in the original file.");
n = reader.NumberOfPages
End If
End While
' step 5: we close the document
document.Close()
Catch e As Exception
Dim strOb As String = e.Message
End Try
End Sub
Public Function CountPageNo(strFileName As String) As Integer
' we create a reader for a certain document
Dim reader As New PdfReader(strFileName)
' we retrieve the total number of pages
Return reader.NumberOfPages
End Function
End Class
To convert the documents use a third party library like Apose Words for .net. Create a separate class as converter and a function ConvertDocument(ByRef docPath As String, ByRef expPath As String) . If you already have all the files in pdf you dont need to convert them...
you only need to merge them
I hope this codes will help many people

How to save image to folder

I am using webservice to call method in businesslogics(one class written in vb).I am getting inputppath and path to where i have to save image in that method.I have to create thumbnail and also i have to save original image.Means i want to save masterimage in one folder and its thumnail in different folder. I used following code
Public Function CreateThumbNails(ByVal intWidth As Integer, ByVal strInputFilePath As String, ByVal strFileName As String, ByVal strOutputFilePath As String) As String
Dim lnWidth As Integer = intWidth
Dim lnHeight As Integer = 100
Dim bmpOut As System.Drawing.Bitmap = Nothing
Try
Dim loBMP As New Bitmap(strInputFilePath)
Dim lnRatio As Decimal
Dim lnNewWidth As Integer = 0
Dim lnNewHeight As Integer = 0
If loBMP.Width < lnWidth AndAlso loBMP.Height < lnHeight Then
lnNewWidth = loBMP.Width
lnNewHeight = loBMP.Height
End If
If loBMP.Width > loBMP.Height Then
lnRatio = CDec(lnWidth) / loBMP.Width
lnNewWidth = lnWidth
Dim lnTemp As Decimal = loBMP.Height * lnRatio
lnNewHeight = CInt(lnTemp)
Else
lnRatio = CDec(lnHeight) / loBMP.Height
lnNewHeight = lnHeight
Dim lnTemp As Decimal = loBMP.Width * lnRatio
lnNewWidth = CInt(lnTemp)
End If
' *** This code creates cleaner (though bigger) thumbnails and properly
' *** and handles GIF files better by generating a white background for
' *** transparent images (as opposed to black)
bmpOut = New Bitmap(lnNewWidth, lnNewHeight)
Dim g As Graphics = Graphics.FromImage(bmpOut)
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight)
g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight)
loBMP.Dispose()
bmpOut.Save(HttpContext.Current.Server.MapPath(strOutputFilePath) + strFileName)
bmpOut.Dispose()
Return strOutputFilePath + strFileName
Catch e As Exception
Throw New Exception("ThumbNail Creation Failed")
Return ""
End Try
End Function
What code i have to include to save original size image in another folder.Can anybody help?
EDIT trigger happy. you don't need to save it from the bitmap. the file is already there. just copy the file.
If I understand your question then you want to save the image from before you manipulate it to a new location on the server.
That file already exists as a file on the server. The file location of that file is passed into your function as a parameter (strInputFilePath).
The simplest thing to do would to use File.Copy() to copy the file to the desired location.

Resources