How to make pdf file size with respect to div height and width using wkhtmltopdf.exe - vb.net

I tried to make pdf with wkhtmltopdf.exe by supplying html string and is working properly.But i want to provide pdf custom size to exe.
eg:-
Suppose i have a div of height 30 and width 50. then the generated pdf should be of same size.
Below is the code which i found from this website forum
Private Sub WritePDF(ByVal HTML As String)
Dim inFileName As String, outFileName As String, tempPath As String
Dim p As Process
Dim stdin As System.IO.StreamWriter
Dim psi As New ProcessStartInfo()
tempPath = Server.MapPath("~") + "\Uploads\"
inFileName = Session.SessionID + ".htm"
outFileName = Session.SessionID + ".pdf"
' run the conversion utility
psi.UseShellExecute = False
'psi.FileName = "c:\Program Files (x86)\wkhtmltopdf\wkhtmltopdf.exe"
psi.FileName = Server.MapPath("~") + "\App_Data\wkhtmltopdf.exe"
psi.CreateNoWindow = True
psi.RedirectStandardInput = True
psi.RedirectStandardOutput = True
psi.RedirectStandardError = True
' note that we tell wkhtmltopdf to be quiet and not run scripts
' NOTE: I couldn't figure out a way to get both stdin and stdout redirected so we have to write to a file and then clean up afterwards
psi.Arguments = "-q -n - " & tempPath & outFileName
p = Process.Start(psi)
Try
stdin = p.StandardInput
stdin.AutoFlush = True
stdin.Write(HTML)
stdin.Close()
If p.WaitForExit(15000) Then
' NOTE: the application hangs when we use WriteFile (due to the Delete below?); this works
'Response.WriteFile(tempPath + outFileName);
Response.BinaryWrite(System.IO.File.ReadAllBytes(tempPath & outFileName))
End If
Finally
p.Close()
p.Dispose()
End Try
' delete the pdf
System.IO.File.Delete(tempPath & outFileName)
End Sub

If you want to use a standard paper size you can use the --page-size argument and provide the page size name (A4, Letter, etc.). If you want a custom page size, you can use the --page-width and --page-height arguments (e.g. --page-width 100mm --page-height 200mm).
By default, wkhtmltopdf will add a margin around each side of the page, which is used to render the header and footer in. To change the page margins, use the arguments --margin-top, --margin-right, --margin-bottom and --margin-left.
Another thing to note is the --disable-smart-shrinking; by default, wkhtmltopdf will 'guess' the dpi of the pdf by calculating the html widths and trying to fit it within the boundaries of the pdf page. If you want to precisely measure each element on the page, you should add --disable-smart-shrinking to your argument list. However, make sure the html output defines the exact size of the html page (which should be the same as the pdf page minus the page margins), otherwise wkhtmltopdf might not be able to render the page properly.

Related

Manipulating FedEx label in vb.net API

I am writing a FedEx API in vb.net to work with our universe database. So far everything is about done but i'm stuck on the printing label part. The code FedEx gave me saves the label image as a pdf and prints from acrobat. Problem is you can't really do anything with a pdf image, or so i'm sure of at least, meaning i can't line the image up correctly on a 4 x 6 thermal label. How would i do this or is there a good way to just use the image and assign x and y coordinates without messing up the FedEx label? here is the code from where it saves the label down to print:
Sub ShowShipmentLabels(ByRef CompletedShipmentDetail As CompletedShipmentDetail, ByRef packageDetail As CompletedPackageDetail, ByVal isCodShipment As Boolean)
If (packageDetail.Label.Parts(0).Image IsNot Nothing) Then
' Save outbound shipping label
Dim FileName As String = getProperty("labelpath") + packageDetail.TrackingIds(0).TrackingNumber + ".pdf"
SaveLabel(FileName, packageDetail.Label.Parts(0).Image)
Mylabel.Print()
' Save COD Return label
If (isCodShipment) Then
FileName = getProperty("labelpath") + CompletedShipmentDetail.CompletedPackageDetails(0).TrackingIds(0).TrackingNumber + "CR.pdf"
SaveLabel(FileName, CompletedShipmentDetail.CompletedPackageDetails(0).CodReturnDetail.Label.Parts(0).Image)
End If
End If
End Sub
Sub SaveLabel(ByRef labelFileName As String, ByRef labelBuffer() As Byte)
' Save label buffer to file
Dim LabelFile As FileStream = New FileStream(labelFileName, FileMode.Create)
LabelFile.Write(labelBuffer, 0, labelBuffer.Length)
LabelFile.Close()
' Display label in Acrobat
DisplayLabel(labelFileName)
End Sub
Sub DisplayLabel(ByRef labelFileName As String)
Dim info As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo(labelFileName)
info.UseShellExecute = True
info.CreateNoWindow = True
info.WindowStyle = ProcessWindowStyle.Hidden
info.Verb = "Print"
System.Diagnostics.Process.Start(info)
End Sub
If it looks fine on the screen, but is not aligning correctly on the printer then you should probably look to the printer settings either on the device itself or in the driver. I would with the driver, you probably need to specificy the media and maybe adjust the margins.
Chris, if this hasn't been solved yet, check out this FAQ from our database at Shippo: http://support.goshippo.com/hc/en-us/articles/203804319-My-labels-are-not-printing-correctly-How-can-I-fix-this-
Printing 4x6 can be a bit of a headache at first. If it's not yet working for you, feel free to comment with more details what printer you use and your printer settings. This would help to debug further.
You have the option to save the image in ZPLII format. Do it and save it as tracking_id.zpl.
Share the Zebra printer as FedexThermal.
Then create a print.cmd script on he fly from vb to execute...
COPY /B tracking_id.zpl \\localhost\FedexThermal
Then in vb create a process to run that script,
Works for me.

Printing a document from VB

I have an app which monitors a network location for new documents.
They can be word documents, PDF files, spreadsheets etc.
When a document is detected, it is copied to a local folder within c:\Temp.
What I need is for the document, once copied, to be sent to a specified (not default) printer.
Has anyone got any ideas on how I can achieve this?
Thanks!!
You may need to create a variety of functions to print your document. Like using LPR to print PDF or PostScript, Microsoft.Office.Interop for Word and Excel documents, and so on...
If it were me, I would use System.IO.Path.GetExtension(filename) to determine the file type and then call whichever function was most appropriate...or log that the file was not printable if the format was not handled.
Microsoft.Office.Interop
Using Microsoft.Office.Interop.Excel, you can call the PrintOutEx method on a Workbook or Worksheet and specify which printer to use.
See:
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.worksheets.printoutex.aspx
and
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._workbook.printoutex.aspx
With Microsoft.Office.Interop.Word you can set the ActivePrinter property of the Application and then use the PrintOut method on the Document.
See:
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word._application.activeprinter.aspx
and https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word._document.printout.aspx
LPR
I wrote a tool once that prints PDF and PostScript files. The code was something like:
'Set the IP address of the printer to use.
If printer1 Then
printserver = printer1Address
ElseIf printer2 Then
printserver = printer2Address
ElseIf printer3 Then
printserver = printer3Address
End If
'Use LPR to print the file.
Dim lprProcess As New Process()
With lprProcess.StartInfo
.UseShellExecute = False
.FileName = "CMD"
.Arguments = "/c LPR -s " & printserver & " -P P3 " & myNewFileName
End With
lprProcess.Start()
LPR is not a included by default in Windows 7 and above, but it is a cake-walk to turn on. See steps 1-3 on http://campus.mst.edu/cis/desktop/documentation/pc/win7_x64/lpr_printer/install.htm

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

Print rdlc report without viewing print dialogue box

I have am writing a POS application, which requires to print invoice very often.
I need to send it directly to printer instead of viewing the print dialogue. Using Reportviewer_renderingcomplete, I can avoid seeing the report but I do not know how to avoid seeing the print dialogue box and print report without user intervention?
Thanks a lot.
Here is how you can do it:
Dim m_currentPageIndex As Integer
Private m_streams As IList(Of Stream)
Dim report As New LocalReport()
report.DataSources.Add(New ReportDataSource("testData", reportData.Tables(0)))
report.ReportEmbeddedResource = "ReportsLibrary.rptTestData.rdlc"
Dim deviceInfo As String = "<DeviceInfo><OutputFormat>EMF</OutputFormat><PageWidth>8.5in</PageWidth><PageHeight>11in</PageHeight><MarginTop>0.25in</MarginTop><MarginLeft>0.25in</MarginLeft><MarginRight>0.25in</MarginRight><MarginBottom>0.25in</MarginBottom></DeviceInfo>"
Dim warnings As Warning()
m_streams = New List(Of Stream)()
report.Render("Image", deviceInfo, CreateStream, warnings)
For Each stream As Stream In m_streams
stream.Position = 0
Next
Dim printDoc As New PrintDocument()
printDoc.PrinterSettings.PrinterName = "<your default printer name>"
Dim ps As New PrinterSettings()
ps.PrinterName = printDoc.PrinterSettings.PrinterName
printDoc.PrinterSettings = ps
printDoc.PrintPage += New PrintPageEventHandler(PrintPage)
m_currentPageIndex = 0
printDoc.Print()
Where PrintPage defined as follows:
' Handler for PrintPageEvents
Private Sub PrintPage(sender As Object, ev As PrintPageEventArgs)
Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
' Adjust rectangular area with printer margins.
Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX), ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY), ev.PageBounds.Width, ev.PageBounds.Height)
' Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
' Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect)
' Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex += 1
ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
End Sub
This is an interesting walkthrough by Microsoft: Printing a Local Report without Preview.
It's a different approach from yours because it prints directly a report without using ReportViewer and RenderingComplete event.
In order to not display PrintDialog box you must set printDoc.PrinterSettings.PrinterName with your default printer name.
Maybe you can store this value in a user configuration file.
It is actually far more simple than you would have imagined.
Within your form, include a "PrintDocument" component from the Toolbox.
Within your code behind, you will want to call the following method on your newly added component.
PrintDoc.Print()
The documentations state that the Print() "Starts the document's printing process". It will automatically begin printing the default set printer.
As tezzo mentioned, to set the Printer manually you can use the following snippet:
PrintDoc.PrinterSettings.PrinterName = "YourPrinterNameHere"
PrintDoc.PrinterSettings.PrinterName "gets or sets the name of the printer to use" as according to documentation. And if you need any further help, check out this video.
Please note however that video does not mention how to print "silently". It is just a good reference for beginners to see how the Print Components work together.

Restrict Image by selecting it's URL

I am trying to add Images from websites and I am facing poblem with an issue which is that when I am trying to go to google images and trying to add some Images and when I right click for some images I find "Copy Image URL" and for some I don't find it and I find "Copy link address".Now I want my users to restrict from adding the Images which contain "Copy Image URL"
And I am attaching Images so that you'll understand me in a better way.
How do I do that?
Here is the code for saving the image:
Dim dir_name As String = txtDirectory.Text
If Not dir_name.EndsWith("\") Then dir_name &= "\"
For Each pic As PictureBox In flpPictures.Controls
Dim bm As Bitmap = CType(pic.Image, Bitmap)
Dim filename As String = CStr(pic.Tag)
filename = filename.Substring(filename.LastIndexOf("/") + 1)
Dim ext As String = filename.Substring(filename.LastIndexOf("."))
'Here it gives me an error at(filename.lastindexof(".")
Dim full_name As String = dir_name & filename
Select Case ext
Case ".bmp"
bm.Save(full_name, Imaging.ImageFormat.Bmp)
Case ".gif"
bm.Save(full_name, Imaging.ImageFormat.Gif)
Case ".jpg", "jpeg"
bm.Save(full_name, Imaging.ImageFormat.Jpeg)
Case ".png"
bm.Save(full_name, Imaging.ImageFormat.Png)
Case ".tiff"
bm.Save(full_name, Imaging.ImageFormat.Tiff)
Case Else
MessageBox.Show( _
"Unknown file type " & ext & _
" in file " & filename, _
"Unknown File Type", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Select
Next pic
Beep()
'WEB CLIENT IS NEEDED TO DO THE DOWNLOAD
Dim MyWebClient As New System.Net.WebClient
'BYTE ARRAY HOLDS THE DATA
Dim ImageInBytes() As Byte = MyWebClient.DownloadData(url)
'CREATE A MEMORY STREAM USING THE BYTES
Dim ImageStream As New IO.MemoryStream(ImageInBytes)
'CREATE A BITMAP FROM THE MEMORY STREAM
PictureBox1.Image = New System.Drawing.Bitmap(ImageStream)
In the top screenshot, you are right-clicking directly on an image.
In the bottom screenshot, you are right-clicking on an empty div with a z-index that puts it above the image.
Here's an example:
<a href="http://example.com">
<img src="myImg.jpg" style="position: absolute;" />
<div style="z-index:1; position:absolute; width:100%; height:100%;"></div>
</a>
When you mouse over the link in Google Images another div is shown on top that contains the saveable image. Have a look with Firebug and see for yourself :)
Note that there is no perfect way to prevent users from saving images from your website. You can disable right click, mask the image with a div, mask the image with a transparent image (so the user can right-click and save the image but they get the wrong one), prevent caching etc but ultimately any tech savvy user can get around this. Still, these approaches will stop casual users so it's better than nothing. If you want to find out more about the methods that I just named, I suggest Googling for "disable save image as" or "disable copy image url".
maybe helpful
Sub Base64Convert(ByVal Base64MSG As String)
'Setup image and get data stream together
Dim img As System.Drawing.Image
Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream
Dim b64 As String = Base64MSG
Dim b() As Byte
'Converts the base64 encoded msg to image data
b = Convert.FromBase64String(b64)
MS = New System.IO.MemoryStream(b)
'creates image
img = System.Drawing.Image.FromStream(MS)
'writes image for displaying
img.Save(Request.ServerVariables("APPL_PHYSICAL_PATH") & "LabelInfo.tiff", System.Drawing.Imaging.ImageFormat.Tiff)
'cleaning up house
img.Dispose()
MS.Close()
End Sub