Visual Basic: DragDrop jpg pic from browser - jpeg

FileDrop works for dragging a file from File Explorer:
Private Sub lvwPics_DragDrop(sender As Object, e As DragEventArgs) Handles lvwPics.DragDrop
Const TMPFILE As String = "c:\temp\pads\dragtmp.jpg"
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
ProcessDragDropPaste(e.Data.GetData(DataFormats.FileDrop))
Else
My.Computer.FileSystem.WriteAllBytes(TMPFILE, e.Data.GetData(DataFormats.Bitmap), False)
Not sure how to get data when dragging .jpg file from browser. Why no DataFormats for jpg? (e.Data.GetData(DataFormats.Bitmap) is Nothing)

Related

How do i save a pdf file to a desktop directory using vb.net?

I am creating a PDF form in vb.net and saving it to my desktop. The user inputs a name into the textbox and when they click the button the pdf file is created and saved to my desktop.
The issue I am having is that the pdf is being saved like this:
Desktop0001report.pdf
I do not understand why "Desktop" is showing in the front. Is there a way to fix this?
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim pdfdoc As New Document(PageSize.A4, 15, 15, 30, 30)
Dim filename As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + TextBox1.Text + " report.pdf"
Dim file As New FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)
PdfWriter.GetInstance(pdfdoc, file)
pdfdoc.Open()
FillPDF(pdfdoc)
pdfdoc.Close()
Process.Start(filename)
Catch ex As Exception
MessageBox.Show("PDF could not be generated!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
End Class
Use System.IO.Path.Combine to assemble paths with directory separators included.
Dim filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
TextBox1.Text & " report.pdf")
The function takes a ParamArray argument, so you can provide an arbitrary number of strings to be combined into a single path.
I always try to use methods from System.IO.Path when I'm manipulating file paths. There aren't methods for absolutely everything I've needed to do, but most of the common operations are covered.
Change this line to (note the added slash):
Dim filename As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\" + TextBox1.Text + " report.pdf"

How to add image file as Ole object in excel using java

I tried with Aspose cell.
But I am able to add pdf file properly.
When I add jpg file, it shows in the excel file but doesnot get opened.
I tried with following way.
sheet.getOleObjects().get(oleObjectIndex).setImageData(binary);
sheet.getOleObjects().get(oleObjectIndex).setLeftCM(oleObjectIndex);
sheet.getOleObjects().get(oleObjectIndex).setDisplayAsIcon(true);
Here image shown like a thumbnail , but I dont want that.
sheet.getOleObjects().get(oleObjectIndex).setObjectData(binary);
//sheet.getOleObjects().get(oleObjectIndex).setFileType(oleFileType);
sheet.getOleObjects().get(oleObjectIndex).setDisplayAsIcon(true);
sheet.getOleObjects().get(oleObjectIndex).setLeftCM(oleObjectIndex);
Here it shows proper icon for the file but file does not get opened when double clicked.
Help from the community is highly apraciated.
Thank you.
See the following two lines of code that you also need to add:
sheet.getOleObjects().get(oleObjectIndex).setFileFormatType(FileFormatType.UNKNOWN);
sheet.getOleObjects().get(oleObjectIndex).setObjectSourceFullName(path);
Here is complete sample code that I tested and it works fine:
e.g
Sample code:
// Get the image file.
String path = "e:\\test\\myfile.jpg";
File file = new File(path);
// Get the picture into the streams.
byte[] img = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(img);
// Instantiate a new Workbook.
Workbook wb = new Workbook();
// Get the first worksheet.
Worksheet sheet = wb.getWorksheets().get(0);
// Add an Ole object into the worksheet with the image shown in MS Excel.
int oleObjIndex = sheet.getOleObjects().add(14, 3, 200, 220, img);
OleObject oleObj = sheet.getOleObjects().get(oleObjIndex);
// Set embedded ole object data and other attributes.
oleObj.setObjectData(img);
oleObj.setDisplayAsIcon(true);
oleObj.setFileFormatType(com.aspose.cells.FileFormatType.UNKNOWN);
oleObj.setObjectSourceFullName(path);
// Save the excel file
wb.save("f:\\files\\tstoleobject1.xlsx");
Hope, this helps a bit.
PS. I am working as Support developer/ Evangelist at Aspose.
i just use the same code,but i found when i open the new Excel,it shows as a image,i have to check it twice to transfer it to an OLE.
whats worry

Download xls file to client from Datatable

I am developing a website on VisualStudio using VB. In one section of my site I make a DataBase Query, store the result in a DataTable and display it. I give the user the option of dowloading the information, what I would like to do is to download an XLS file to the client's side with the information in the datatable without creating the xls on the server side.
I currently have the following code section to send the file to the user
Dim fileToDownload = Server.MapPath("~/docs/QuejometroVF.pdf")
Response.ContentType = "application/octet-stream"
Dim cd = New ContentDisposition()
cd.Inline = False
cd.FileName = Path.GetFileName(fileToDownload)
Response.AppendHeader("Content-Disposition", cd.ToString())
Dim fileData = System.IO.File.ReadAllBytes(fileToDownload)
Response.OutputStream.Write(fileData, 0, fileData.Length)
But it requires a path to a local file in order to send it.
First I would like to know how to create a xls file from the datatable (only in memory) and then send that object as a file to the client's computer. If it is not possible, Could you tell me how to write the xls file in my server so I can then send it using the code above? I have not really figured out how to do it yet.
I was thinking on doint it that way because I don't want to keep files in the server when I already have that information on the database and I don't pretend on keeping that file stored.
Thank you
I export data to xls file using the following code, my backend is an Oracle database and that's where I get the data:
Dim MyConnection As OracleConnection = OpenConnection(Session("USERNAME"), Session("PASSWORD"))
Dim MyDataSet As New DataSet
MyDataSet = GetExportData(MyConnection, Session("UserDataKey"), Session("CompoundKey"), Session("LastOfCompoundKey"))
'I rename the dataset's table columns to what I want in the xls file
MyDataSet.Tables!data.Columns(0).ColumnName = "IDNumber"
MyDataSet.Tables!data.Columns(1).ColumnName = "FirstName"
MyDataSet.Tables!data.Columns(2).ColumnName = "LastName"
MyDataSet.Tables!data.Columns(3).ColumnName = "Address"
MyDataSet.Tables!data.Columns(4).ColumnName = "City"
MyDataSet.Tables!data.Columns(5).ColumnName = "State"
MyDataSet.Tables!data.Columns(6).ColumnName = "ZipCode"
MyDataSet.Tables!data.Columns(7).ColumnName = "Phone_Area"
MyDataSet.Tables!data.Columns(8).ColumnName = "Phone_Prefix"
MyDataSet.Tables!data.Columns(9).ColumnName = "Phone_Suffix"
MyDataSet.Tables!data.Columns(10).ColumnName = "Email"
MyDataSet.Tables!data.Columns(11).ColumnName = "BirthDay"
Response.ClearContent()
'I create the filename I want the data to be saved to and set up the response
Response.AddHeader("content-disposition", "attachment; filename=" & Replace(Session("Key0"), " ", "-") & "-" & Session("Key1") & "-" & Replace(Replace(Trim(Session("Key2")), ".", ""), " ", "-") & ".xls")
Response.ContentType = "application/excel"
Response.Charset = ""
EnableViewState = False
Dim tw As New System.IO.StringWriter
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
'Create and bind table to a datagrid
Dim dgTableForExport As New DataGrid
If MyDataSet.Tables.Count > 0 Then
If MyDataSet.Tables(0).Rows.Count > 0 Then
dgTableForExport.DataSource = MyDataSet.Tables(0) ' .DefaultView
dgTableForExport.DataBind()
'Finish building response
Dim strStyle As String = "<style>.text { mso-number-format:\#; } </style>"
For intTemp As Integer = 0 To MyDataSet.Tables(0).Rows.Count - 1
For intTemp2 As Integer = 0 To MyDataSet.Tables(0).Columns.Count - 1
dgTableForExport.Items(intTemp).Cells(intTemp2).Attributes.Add("class", "text")
Next
Next
End If
End If
dgTableForExport.RenderControl(hw)
Response.Write(style)
' Write the HTML back to the browser.
Response.Write(tw.ToString())
Response.End()
'Close, clear and dispose
MyConnection.Close()
MyConnection.Dispose()
MyConnection = Nothing
I copied and pasted this from one of my projects, it's untested and may contain error but should get you started.
You can use a MemoryStream or to write the file to Response stream using Response.Write method.
Creating an excel file from a data table is fairly easy as you can just create a GridView and bind the table to it.
Here is a code snippet that does what you need.
Public Sub DownloadExcel(outputTable as System.Data.DataTable)
Dim gv As New GridView
Dim tw As New StringWriter
Dim hw As New HtmlTextWriter(tw)
Dim sheetName As String = "OutputFilenameHere"
gv.DataSource = outputTable
gv.DataBind()
gv.RenderControl(hw)
Response.AddHeader("content-disposition", "attachment; filename=" & sheetName & ".xls")
Response.ContentType = "application/octet-stream"
Response.Charset = ""
EnableViewState = False
Response.Write(tw.ToString)
Response.End()
End Sub
There are a few issues with this method:
This doesn't output a native excel file. Instead, it outputs the HTML for a GridView that Excel will detect and notify the user that the content doesn't match the extension. However, it WILL display in Excel correctly if the user selects 'Yes' from the dialog box.
Earlier versions of Firefox and Chrome didn't like this method and instead download the file with a .html extension. I just tested it in both browsers and it worked with the most up to date versions.
Ideally, you should probably use Excel on your webserver to create native spreadsheets, but this will work if you (like me) don't have the means to do so.

Editing a Hex Stream in VBA Before Saving to File

Background: I am extracting a file that is saved in a SQL database using an ADODB connection. One column of the database is the filename, including the file extension, and another is the actual contents of the file as a hex stream. I would like to save this file and open it.
Problem: This works fine with .pdf files. However, with .png files there is an error- the file is corrupted when I try to open it. I used a hex editor (HxD) and noticed that there were excess values. If I remove these the file opens fine. The hex stream should begin with the "per mille" character (Chr(137) in excel) in order for the file to open. I have not found a way to edit the hex stream in excel without converting it to characters.
The .png file opens with no problem when I take out the first few characters using a hex editor so that the file begins with:
‰PNG
Or the equivalent in hex code:
89 50 4E 47
The excess characters are
ÿþ
Or the equivalent in hex code:
FF FE
(I am trying to remove these). These characters are in the saved file even when I remove 4 characters from the text string using
Content = Right(Content, Len(Content) - 4)
It's almost like they automatically get added before the string when I save the file.
Code:
Calling the save to file function, where Content is the file content and Name is the filename:
Call StringToTextFile("C:\", rst![Content], rst![Name])
The function is below:
Public Sub StringToTextFile(ByVal directory As String, ByVal Content As String, ByVal filename As String)
'Requires reference to scrrun.dll
Dim fso As Scripting.FileSystemObject
Dim ts As Scripting.TextStream
Set fso = New Scripting.FileSystemObject
If Right(filename, 4) = ".png" Then 'recognizing the .png file
'Content = CByte(Chr(137)) & Right(Content, Len(Content)) 'unsuccessful attempt at inserting "per mille" character
'iret = InStr(0, Chr(137), Content, vbBinaryCompare) 'unsuccessful attempt at finding the "per mille" character in the content
End If
Set ts = fso.CreateTextFile(directory & filename, True, True)
ts.Write Content
ts.Close
Dim myShell As Object
Set myShell = CreateObject("WScript.Shell")
myShell.Run directory & filename 'Open the saved file
End Sub
When I try to insert the "per mille" character using Chr(137) it just shows a blank space in the hex editor.
Any help is appreciated!
This seems to be a similar discussion, but I am unsure how to apply this to my case:
excel-vba-hex-to-ascii-error

How to copy a picture (graphic object) to the Clipboard in VBA?

In Excel 2003, I need to copy a Graphics object (sheet.PageSetup.LeftFooterPicture) to the Clipboard.
How can I do that?
In Excel versions prior to 2007, you cannot extract the graphic from the footer. You would need to have the original image file.
See this previous question for more details
According to MSDN a Graphic loads the Image through a file (filename). The Filename should contain the whole path to the file like 'C:\myimage.jpg' but once the worksheet is saved it changed the filename to 'myiamge' without the path and the extension. I wasn't able to find any other Reference to the file within Excel.
The following code might help you.
Sub yourMethod()
copyGraphic Me.PageSetup.LeftFooterPicture
End Sub
Sub copyGraphic(srcGraphic As Graphic)
Dim imagefolder As String
Dim imageExtension As String
Dim imagePath As String
imagefolder = "D:\" '"
imageExtension = ".gif"
If InStr(1, srcGraphic.filename, ".") Then
imagePath = srcGraphic.filename
Else
imagePath = imagefolder & srcGraphic.filename & imageExtension
End If
Me.Shapes.AddPicture imagePath, False, True, 10, 10, Round(srcGraphic.Width, 0), Round(srcGraphic.Height, 0)
End Sub
You might want to change Me. to the Name of your Sheet and the Destination Sheet.
as it mentioned before the problem is that I cannot extract picture from graphic object(LeftFooterPicture)
Looking on the answers I did muddle through this issue.
The Filename should contain the whole path to the file like 'C:\myimage.jpg' but once the worksheet is saved it changed the filename to 'myiamge' without the path and the extension.
so here is my workaround:
Before 'Save' event I scan all worksheets and get their Graphic to that time "Filename" has right content (absolute path like C:\mypic.jpg)
I create a hiden worksheet and add all pictures as Shape objects (Shapes.AddPicture with picture's path)
I bind a current workshhet name and picture position with shape name
By the time I need to copy a picture to cliapboard I look up the picture in the hiden page (shape.CopyPicture xlScreen, xlPicture)
When I try to copy something that doesn't seem to want to copy, I do a Print Screen from my keyboard and then paste it to the PAINT accessory. From there, you can crop out anything you don't want and then cut and paste the new image into a new PAINT file so it is clean. You can save it in a .jpg for easier use.
Hope that helps.
Private Sub Command1_Click()
Clipboard.Clear
Clipboard.SetData Picture1.Picture, vbCFBitmap
Command1.Enabled = False
End Sub
Like this you can copy pictures to the clipboard.

Resources