Generating PDF from Base64 Byte Array in VBA - vba

I have the following JSON response from a webservice method which will return byte[] in PDF format:
JVBERi0xLjQKJeLjz9MKMSAwI......nVq2P63zkirBH1z9aW3pDxn6F7q9TFV==
The return value is a byte() array. I been trying for a few days trying to use the function available in one of the questions posted in "Generating PDF from Base64 string in VBA" to generate PDF from the above Base64 Byte array, but I couldn't.
What I have done is that based on the return byte array from the webservice method, I save it as a byte array variable name b64testByte. Subsequently, I then proceed to call 2 methods in my program, namely encodeBase64 first, and followed by DecodeBase64. The PDF file is generated. However, when I try to open the file, there is an error which reads "Error: the document is damaged and cannot be repaired. Adobe Reader could not open because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)."
Dim b64testByte() As Byte
b64testByte = xmlhttp.responseText
Dim B64String As String
B64String = encodeBase64(b64testByte)
Dim FilePath As String
FilePath = "D:\label.pdf"
Open FilePath For Binary Access Write As #1
Put #1, 1, DecodeBase64(B64String)
Close #1
Private Function DecodeBase64(ByVal strData As String) As Byte()
Dim objXML As Object 'MSXML2.DOMDocument
Dim objNode As Object 'MSXML2.IXMLDOMElement
'get dom document
Set objXML = CreateObject("MSXML2.DOMDocument")
'create node with type of base 64 and decode
Set objNode = objXML.createElement("b64")
objNode.DataType = "bin.base64"
objNode.Text = strData
DecodeBase64 = objNode.nodeTypedValue
'clean up
Set objNode = Nothing
Set objXML = Nothing
End Function
Private Function encodeBase64(ByRef arrData() As Byte) As String
Dim objXML As Object 'MSXML2.DOMDocument
Dim objNode As Object 'MSXML2.IXMLDOMElement
'get dom document
Set objXML = CreateObject("MSXML2.DOMDocument")
Set objNode = objXML.createElement("b64")
objNode.DataType = "bin.base64"
objNode.nodeTypedValue = arrData
encodeBase64 = objNode.Text
Set objNode = Nothing
Set objXML = Nothing
End Function**

Related

extract rich text field from PDF using vb to MS Access

I'm looping through files and I have a fillable PDF form that I am extracting data from. Everything works except when I extract from a rich text field. I get the data, but it looses its formatting.
My code is below. For example, 'General_Match_Comments' is my rich text field in the PDF, but when it comes into the Access Database, it is missing the formatting such as multi-line
Dim AcroApp As Acrobat.CAcroApp
Dim theForm As Acrobat.CAcroPDDoc
Dim jso As Object
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Set AcroApp = CreateObject("AcroExch.App")
Set theForm = CreateObject("AcroExch.PDDoc")
Set oFolder = oFSO.GetFolder(varfolder)
For Each oFile In oFolder.Files
theForm.Open (oFile)
Set jso = theForm.GetJSObject
Dim rstblEvalHeader As Recordset
Set rstblEvalHeader = CurrentDb.OpenRecordset(Name:="tblEvalHeader", Type:=RecordsetTypeEnum.dbOpenDynaset)
With rstblEvalHeader
.AddNew
' get the information from the form fields Text1 and Text2
!Referee = jso.getField("Referee").Value
!EvalDate_af_date = jso.getField("EvalDate_af_date").Value
!Position = jso.getField("R1R2").Value
!Event_Site = jso.getField("Event_Site").Value
!Partner = jso.getField("Partner").Value
!Level_of_Play = jso.getField("Level_of_Play").Value
!Time_Court = jso.getField("Time_Court").Value
!Teams = jso.getField("Teams").Value
!Observer = jso.getField("Observer").Value
!Match_Scores = jso.getField("Match_Scores").Value
!Match_Difficulty = jso.getField("Match_Difficulty").Value
!General_Match_Comments = jso.getField("General_Match_Comments").Value
!Result = jso.getField("Result").Value
strGUID = !ID
strGUID = Replace(Replace(strGUID, "{guid ", ""), "}}", "}")
!SID = strGUID
.Update
End With
theForm.Close
Next oFile

Download output (XML) from URL, then parse the XML to get the data?

I'm trying to download the XML data outputted by Google Map API. After I download and store that data in a variable, I would like to parse that data to get a specific information. Here is the link to a sample output : http://maps.googleapis.com/maps/api/geocode/xml?latlng=34.6465583799,-101.57620022
Dim oXMLHTTP As Object
Dim sPageHTML As String
Dim sURL As String
Dim XmlMapResponse As String
sURL = "http://maps.googleapis.com/maps/api/geocode/xml?latlng=" + Selection.Value
Set oXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
oXMLHTTP.Open "GET", sURL, False
oXMLHTTP.send
XmlMapResponse = oXMLHTTP.responseText
Once the XML data has been downloaded, I tried to parse out "79088" which is the postal code by doing this :
Dim strXML As String
Dim xNode As IXMLDOMNode
Dim XDoc As MSXML2.DOMDocument
strXML = XmlMapResponse
Set XDoc = New MSXML2.DOMDocument
If Not XDoc.LoadXML(strXML) Then
Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
End If
Set xNode = XDoc.SelectNodes("/GeocodeResponse/result/address_component/long_name")
MsgBox xNode.InnerText(6)
I don't know why xNode.InnerText(6) doesn't work for me. In VB.NET it works fine.
Any help?
SelectNodes returns a node list, not a single node.
Maybe you meant to use:
Set xNode = XDoc.SelectNodes( _
"/GeocodeResponse/result/address_component/long_name")(6)
As previously mentioned SelectNodes returns a node list which caused an error when I attempted to run this code.You should either:
change xNode to a IXMLDOMNodeList
Select only a single node from the list (as suggested by Tim)
Change the function to XDoc.selectSingleNode("/XPATH")
Beyond that, The IXMLDOMNode Object does not appear to support an InnerText function. use xNode.Text instead.
The following code runs without errors and returns the first result (8379)
Sub test()
Dim oXMLHTTP As Object
Dim sPageHTML As String
Dim sURL As String
Dim XmlMapResponse As String
sURL = "http://maps.googleapis.com/maps/api/geocode/xml?latlng=" + "34.6465583799,-101.57620022"
Set oXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
oXMLHTTP.Open "GET", sURL, False
oXMLHTTP.send
XmlMapResponse = oXMLHTTP.responseText
Dim strXML As String
Dim xNode As MSXML2.IXMLDOMNode
Dim XDoc As MSXML2.DOMDocument60
strXML = XmlMapResponse
Set XDoc = New MSXML2.DOMDocument60
If Not XDoc.LoadXML(strXML) Then
Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
End If
Set xNode = XDoc.SelectSingleNode("/GeocodeResponse/result/address_component/long_name")
MsgBox xNode.Text
End Sub

Preserve Exif/Image Properties

In a web app, users can upload images, which save on the server. It creates thumbnails of the image on the back end with the following code, but all exif data of the image is lost.
I want to preserve the exif data from the original image all throughout the process, and have it included in the final stream. I can read the exif properties from the image, but can't get it to preserve when saving.
To clarify, I am not trying to read, parse, or do anything specific to the metadata itself, I just want to preserve it exactly as it was in the original image during image processing.
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'prepare image
Dim imgFullSize As System.Drawing.Image
'attempt to get the image
Dim sInputURL As String = HttpUtility.UrlDecode(Request.QueryString("IptFl"))
If InStr(sInputURL, "http://") > 0 Or InStr(sInputURL, "https://") Then
'from web url
Dim imgWebRequest As System.Net.WebRequest
Dim imgWebResponse As System.Net.WebResponse
imgWebRequest = System.Net.WebRequest.Create(sInputURL)
imgWebResponse = imgWebRequest.GetResponse()
imgFullSize = System.Drawing.Image.FromStream(imgWebResponse.GetResponseStream())
Else
'from file
imgFullSize = System.Drawing.Image.FromFile(Server.MapPath(sInputURL))
End If
' Dim props As PropertyItem() = imgFullSize.PropertyItems
' For Each prop As PropertyItem In props
' Response.Write(prop.Id.ToString() & "<br />")
' Next
'determine type
Dim sFileExtension As String = "png"
If Left(Right(sInputURL, 4), 1) = "." Then sFileExtension = Right(sInputURL, 3) 'for jpg, gif, etc
If Left(Right(sInputURL, 5), 1) = "." Then sFileExtension = Right(sInputURL, 4) 'for tiff, jpeg, etc
Dim jpgEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
Dim gifEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Gif)
Dim pngEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Png)
'set the quality
Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality
Dim myEncoderParams As New EncoderParameters(1)
Dim myEncoderQuality As New EncoderParameter(myEncoder, CType(100L, Int32))
myEncoderParams.Param(0) = myEncoderQuality
'save img to memory stream
Dim ms As New MemoryStream()
Select Case sFileExtension
Case "jpg" : imgFullSize.Save(ms, jpgEncoder, myEncoderParams)
Case "png", "gif" : imgFullSize.Save(ms, pngEncoder, myEncoderParams)
Case Else : imgFullSize.Save(ms, pngEncoder, myEncoderParams)
End Select
'output the memory stream
Response.ContentType = "image/" & sFileExtension
ms.WriteTo(Response.OutputStream)
'---> when I save the above image and look at the exif, it doesn't exist
End Sub
Private Function GetEncoder(ByVal format As ImageFormat) As ImageCodecInfo
Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageDecoders()
Dim codec As ImageCodecInfo
For Each codec In codecs
If codec.FormatID = format.Guid Then Return codec
Next codec
Return Nothing
End Function
So this did the trick. Basically I had to loop through the source image properties, and for each, set the property in the new image.
'retrieve relative path to image
Dim sSrc As String = HttpUtility.UrlDecode(Request.QueryString("IptFl"))
'prepare image
Dim oImg As System.Drawing.Image
'attempt to get the image, either from web or local file
If InStr(sSrc, "http://") > 0 Or InStr(sSrc, "https://") Then
Dim oRequest As System.Net.WebRequest = System.Net.WebRequest.Create(sSrc)
Dim oResponse As System.Net.WebResponse = oRequest.GetResponse()
oImg = System.Drawing.Image.FromStream(oResponse.GetResponseStream())
oResponse.Close()
Else
oImg = System.Drawing.Image.FromFile(Server.MapPath(sSrc))
End If
'discard if image file not found
If oImg Is Nothing Then Response.End()
Dim sFileExt As String = Split(sSrc, ".")(UBound(Split(sSrc, ".")))
Dim oCanvas As System.Drawing.Bitmap = New System.Drawing.Bitmap(oImg.Width, oImg.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555)
For Each pi As PropertyItem In oImg.PropertyItems
oCanvas.SetPropertyItem(pi)
Next
Dim oGraphic As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(oCanvas)
oGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default
oGraphic.DrawImage(oImg, 0, 0, oImg.Width, oImg.Height)
Dim oStream As System.IO.MemoryStream = New System.IO.MemoryStream()
oCanvas.Save(oStream, System.Drawing.Imaging.ImageFormat.Jpeg)
Response.ContentType = "image/" & sFileExt
'output the memory stream
oStream.WriteTo(Response.OutputStream)
Response.End()

Suggest correction in code to render report

I was suggested the following code to programmatically render SSRS report in PDF format.
I tried it but it is not working.
Can any body suggest what might be required?
Thanks
Dim format As String = "PDF"
Dim fileName As String = "C:\Output.pdf"
Dim reportPath As String = "/[Report Folder]/Invoice"
' Prepare Render arguments
Dim historyID As String = Nothing
Dim deviceInfo As String = Nothing
Dim extension As String = Nothing
Dim encoding As String
Dim mimeType As String = "application/pdf"
Dim warnings() As Microsoft.Reporting.WinForms.Warning = Nothing
Dim streamIDs() As String = Nothing
Dim results() As Byte
ReportViewer1.LocalReport.Render(format, deviceInfo, mimeType, encoding, fileName, streamIDs, warnings)
' Open a file stream and write out the report
Dim stream As FileStream = File.OpenWrite(fileName)
stream.Write(results, 0, results.Length)
stream.Close()
It doesn't work because you never assign anything to the results variable so the FileStream will never get anything written to it. You need to assign the result of the Render method to results:
results = ReportViewer1.LocalReport.Render(format, deviceInfo, mimeType, encoding, fileName, streamIDs, warnings)

Pdf to Tiff file covert in vb.net using PdfSharp.dll

i am using Pdfsharp.dll to convert tiff image to pdf file in vb.net, and it is successfull when i run in my machine, when i use it from other machine, which shows the Error like "Raw string contains invalid character with a value > 255.", please any one help me to fix error,
i using the PdfSharp.dll library and the following code
Dim objDoc As PdfDocument
Dim objPdfPage As PdfPage
Dim objTiffImg As Image
Dim objXImg As XImage
Dim iPageCount As Integer
Dim objXgr As XGraphics
Dim sPdfFile As String = Nothing
Dim objDir As DirectoryInfo
Dim objFile As FileInfo()
Dim objFileInfo As FileInfo
Try
objTiffImageSpliter = New TiffImageSplitter()
objDoc = New PdfDocument
iPageCount = objTiffImageSpliter.GetPageCount(sFileName)
For iCount As Integer = 0 To iPageCount - 1
objPdfPage = New PdfPage
objTiffImg = objTiffImageSpliter.getTiffImage(sFileName, iCount)
objXImg = XImage.FromGdiPlusImage(objTiffImg)
'objPdfPage.Height = objXImg.PointWidth
'objPdfPage.Width = objXImg.PointHeight
objDoc.Pages.Add(objPdfPage)
objXgr = XGraphics.FromPdfPage(objDoc.Pages(iCount))
objXgr.DrawImage(objXImg, 10, 10)
Next
sPdfFile = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\MY_FaxFile\"
If System.IO.Directory.Exists(sPdfFile) Then
objDir = New DirectoryInfo(sPdfFile)
objFile = objDir.GetFiles()
For Each objFileInfo In objFile
objFileInfo.Delete()
Next
sPdfFile &= "MyFax.pdf"
Else
System.IO.Directory.CreateDirectory(sPdfFile)
sPdfFile &= "MyFax.pdf"
End If
objDoc.Save(sPdfFile) ' This Line shows the Error.
objDoc.Close()
Catch ex As Exception
MsgBox(ex.ToString)
sPdfFile = Nothing
End Try
Return sPdfFile
I'm not familiar with this library, but based on your code and error message, I would guess that your App Data folder contains non-ASCII characters and that the PdfSharp library does not support non-ASCII characters in the filename.