Trying to save a pdf file of a screenshot of the form, given a specified location from the user's input - vb.net

I am trying to save a created, PDF file to a location specified by the user. I'm using Visual Studio Community 2019. Essentially, I am taking a screenshot of this form:
And by using the PdfSharp external library, I create a PDF file and then save that PDF to some file location specified by the user. Here is the UI for the user to select their preferred file location:
The issue arises once the program tries to save the PDF file to the location given by the user. Here is the error I get from Visual Studio:
System.NotSupportedException: 'No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.'
I looked online for this specific error, but I don't really understand it nor what to do with it, it's very confusing. I'm still a bit of beginner when it comes to working with Visual Basic. Here's the code that tries to do it:
Dim fileLocation As String
fileLocation = folderBrowseBox.Text
GetFormImage(True).Save(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg", ImageFormat.Jpeg)
' Create new pdf document and page
Dim doc As New PdfDocument()
Dim oPage As New PdfPage()
' Add the page to the pdf document and add the captured image to it
doc.Pages.Add(oPage)
Dim img As XImage = XImage.FromFile(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg")
'Create XImage object from file.
Using xImg = PdfSharp.Drawing.XImage.FromFile(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg")
'Resize page Width and Height to fit image size.
oPage.Width = xImg.PixelWidth * 72 / xImg.HorizontalResolution
oPage.Height = xImg.PixelHeight * 72 / xImg.HorizontalResolution
'Draw current image file to page.
Dim xgr = PdfSharp.Drawing.XGraphics.FromPdfPage(oPage)
xgr.DrawImage(xImg, 0, 0, oPage.Width, oPage.Height)
End Using
doc.Save(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod))
img.Dispose()
The second to last line of code ("doc.Save(fileLocation & ...)") is where the error occurs. The folderBrowseBox.Text (very first line of code) comes from the textbox you see from my second screenshot. Any help/advice will be greatly appreciated!

Try adding this line before writing the PDF file
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance)
Got the idea from here

Related

Open a file in a new instance of program

All;
I have a bit of code I've written that opens a design blueprint when I scan a bar code. It works well enough, but I'd like to open a new instance of the design software (Solidworks) and have the print display in the new instance. Right now, no matter how many Solidworks instances I have open, the print will only open in the first instance started.
The line commented out below is the line that works, just not in the right instance. The line below that is what I'd expect to work, but it returns a 'file not found' even though the path to solidworks and the print path are both correct.
Any explanation as to why this isn't working would be much appreciated as I'm obviously very new at this...and have no idea what I'm doing.
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim barcode As String = tb_barcode.Text
Dim filename As String = tb_barcode.Text
'Add File Extension to end of path
Dim ext As String = ".SLDDRW"
'Split job number from detail number in barcode textbox
barcode = Split(tb_barcode.Text, ".")(0)
filename = Split(tb_barcode.Text, ".")(1)
'- This works, just in primary instance
'System.Diagnostics.Process.Start("G:\Fixtures\" & barcode & "\Details\" & barcode & " DET " & filename & ext)
'- This does not work
System.Diagnostics.Process.Start("'C:\Program files\Solidworks Corp\Solidwork\SLDWORKS.exe' 'G:\Fixtures\" & barcode & "\Details\" & barcode & " DET " & filename & ext + "'")
Catch
MessageBox.Show("File Not Found")
End Try
End Sub
Sorry for naive approach but shouldn't there be a comma in Process.Start between 2 arguments?
Start(String, String)
Starts a process resource by specifying the name of an application and a set of command-line arguments, and associates the resource with a new Process component. docs
Why don't you use the Application.ExecutablePath.That returns the Application's path with its full name. Then your code should be
System.Diagnostics.Process.Start(Application.Executablepath, "G:\Fixtures\" & barcode & "\Details\" & barcode & " DET " & filename & ext + "'")
Also make sure that the second string argument is a valid path.

VBA + Adobe Acrobat SDK - Unable to save an empty page?

I am using VBA as a platform to do some PDF manipulation. The issue I am having is that I cannot seem to get the PDF object to save if the PDF object have not been opened. Below is a snippet of the code that inserts pages to the PDF object, and then saves the pdf object. In terms of the code, I have determined that it works since I have tested the save method with the same input with another pdf object and it worked just fine. Can someone help by explaining why it doesn't allow me to save the object?
Thanks!
Dim NewPDF As New Acrobat.AcroPDDoc
Set NewPDF = CreateObject("AcroExch.PDDoc")
If NewPDF.InsertPages(j, OriPDF, j, 1, 0) Then MsgBox "Success"
If NewPDF.Save(PDSaveLinearized, WritePath & "\" & sh.Cells(StartRow + j - 1, i).Value & ".pdf") Then MsgBox "Success"
NewPDF.Close
Set NewPDF = Nothing
When the above code was ran, neither of the success lines worked as expected.
Change line 3 to this...
If NewPDF.InsertPages(-1, OriPDF, j, 1, 0) Then MsgBox "Success"
The first parameter is the location after which the new pages get inserted but you have no pages because the document is empty so there is no page zero.

MS Word VBA - open file with parameters, string longer than 255 chracters

I'm developing a MS Word macro which needs to open a file on a network drive and pass it the calling file's path as a parameter (i can then retrieve the parameters in the opened file using this method http://www.vbaexpress.com/forum/archive/index.php/t-21174.html).
What i am trying to achieve is the following:
1. Document X (any MS word document) calls document Y (macro document)
2. Document Y processes document X (using the Document object)
3. Document Y closes
The reason i am doing step 1 above is do that users don't have to deploy complex vba code (i am dealing with non IT literate users) and the ease of making updates and enhancements to the code if required.
The following code snippet opens the file with parameters:
Dim currentFilePath As String
currentFilePath = ThisDocument.Path & ThisDocument.Name
Dim MacroFilePath As String
MacroFilePath = ThisDocument.Path & "\Test.docm"
MacroFilePath = """" & MacroFilePath & """" & currentFilePath
Documents.Open (MacroFilePath)
The value of 'MacroFilePath' is gets setup like this (263 chars):
“\\XXXXXXXXXXXX\XX_XX\XXX_XXX XXXX procedural documentation\XX Design Support\Macros - DO NOT MOVE\Work in progress\Calling Document.docm” \\XXXXXXXXXXXX\XX_XX\XXX_XXX XXXX procedural documentation\XX Design Support\Macros - DO NOT MOVE\Work in progress\Test.docm
When I run the above code the error Run-Time '9105': String is longer than 255 characters occurs. I have tested the code where i moved the files to a shorter directory and it works. Is there a way to get around this or another way of achieving what i am trying to do?
Shorting the file paths by saving the documents elsewhere, changing the language i am programming in, or creating any kind of executable is not an option as i am in an enterprise environment.
X can open Y, then call a procedure in Y and pass in it's own path as a parameter.
You can use Application.Run to do this.
See:
https://msdn.microsoft.com/en-us/library/office/ff838935.aspx
Here's the example from that link:
Dim strTemplate As String
Dim strModule As String
Dim strMacro As String
Dim strParameter As String
strTemplate = InputBox("Enter the template name")
strModule = InputBox("Enter the module name")
strMacro = InputBox("Enter the macro name")
strParameter = InputBox("Enter a parameter value")
Application.Run MacroName:=strTemplate & "." _
& strModule & "." & strMacro, _
varg1:=strParameter

saving image type with its original file type

i needed to save an image into my vb proj. I am using a process to save an image to a local folder using it's file name. However, to do it my code has to convert the format to .jpg. What i needed was to save the file with it's original type, since my project will be receiving different image type and maps as well as .pdf in it. is there any way i could change the imageformat.jpegto something else that will save the image to it's original format?
this is the code i am using to save the image.
to create directory
If (Not System.IO.Directory.Exists("d:/Site Images/" & Label33.Text & "/")) Then
System.IO.Directory.CreateDirectory("d:/Site Images/" & Label33.Text & "/")
End If
to save the image
Upload.PictureBox1.Image.Save("d:/Site Images/" & Label33.Text & "/" + Upload.TextBox1.Text, System.Drawing.Imaging.ImageFormat.Jpeg)
i am using MSVisual Studio 2013 Ultimate.
thanks
One method to do this would be that when you load the image into the picturebox you can save the original extension in the tag:
Dim sFilename As String = "c:\test.png" ' However you are populating your picturebox, you can change this variable to the full path of the file
Upload.PictureBox1.Image = Image.FromFile(sFilename)
Upload.PictureBox1.Tag = System.IO.Path.GetExtension(sFilename).ToLower ' Saves the extension to the picturebox in the tag field so that we can evaluate it later
Then when you need to save the image back to a file, you can write it back in the same image format as before:
' Figure out what the original image format was
Dim oImageFormat As System.Drawing.Imaging.ImageFormat
Select Case PictureBox1.Tag.ToString
Case ".jpeg", ".jpg"
oImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg
Case ".png"
oImageFormat = System.Drawing.Imaging.ImageFormat.Png
Case ".bmp"
oImageFormat = System.Drawing.Imaging.ImageFormat.Bmp
Case ".gif"
oImageFormat = System.Drawing.Imaging.ImageFormat.Gif
Case ".tif", ".tiff"
oImageFormat = System.Drawing.Imaging.ImageFormat.Tiff
Case ".ico", ".icon"
oImageFormat = System.Drawing.Imaging.ImageFormat.Icon
Case ".emf"
oImageFormat = System.Drawing.Imaging.ImageFormat.Emf
Case ".exif"
oImageFormat = System.Drawing.Imaging.ImageFormat.Exif
Case ".wmf"
oImageFormat = System.Drawing.Imaging.ImageFormat.Wmf
Case Else
' This should never happen but just in case the extension cannot be found we default to jpeg output
oImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg
End Select
' Save the image with in the proper format again
Upload.PictureBox1.Image.Save("d:/Site Images/" & Label33.Text & "/" & Upload.TextBox1.Text & PictureBox1.Tag.ToString, oImageFormat)
Notes regarding pdf: The Picturebox control does not support pdf files and therefore you will not be able to load pdfs this way. I suggest you convert the pdf to an image file that is supported and then load it into your app after conversion. If this isn't feasible you will have to choose a different control to handle your pdfs such as the WebBrowser control.
You can check the file extension to see what the original image file format is. When you save the file, you can specify the original format in the Picturebox Image.Save function, such as System.Drawing.Imaging.ImageFormat.Png.
If that format is not supported by .net (see link below), you can use a third-party library such as freeImage.
https://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat%28v=vs.110%29.aspx

Open Word Document From Dynamic Directory VB.Net

I have a program for which I have developed a user guide. I have placed this user guide within the project directory. I created a MenuStrip Item by which to open the user guide in Word on the user's machine. I was successfully able to do this with the following code:
Try
userGuide = MSWord.Documents.Open("C:Users\administrator\Documents\VisualStudio2010\Project3\UserGuide.doc")
MSWord.WindowState = Word.WdWindowState.wdWindowStateNormal
MSWord.Visible = True
Catch ex As Exception
MsgBox("An error has prevented the document from opening. The document may not be available." & vbCrLf & vbCrLf & _
"Please try one of the following options:" & vbCrLf & _
"- Check to see if the document is already open" & vbCrLf & _
"- Restart the program")
End Try
The problem is, the path used to open the file will not exist on the users machine. This is a standalone system, so no file share can be created in which to place the document, therefore no common path can be coded.
Is there a way to code dynamic paths? Perhaps something like:
userGuide = MSWord.Documents.Open("%windir%\UserGuide.doc")
Thanks!
if the document will be stored relative to the install path of the application executable, then start with the path of the exe:
Dim path As String
path = System.IO.Path.GetDirectoryName( _
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
Dim docPath as String;
docPath = Path.Combine(path,"UserGuide.doc");