To save Barcode Image In Database and retrieve it - c#

I am trying to save Barcode Image in database. What my code currently generating is just a long string of URL. My code is mentioned below:
string barCode = ds.Tables[0].Rows[0]["productId"].ToString();
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barCode.Length * 40, 80))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
// Font oFont = new Font("Free 3 of 9 Extended", 16);
Font oFont = new Font("IDAutomationHC39M", 16);
PointF point = new PointF(2f, 2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barCode + "*", oFont, blackBrush, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
**// I think Problem is here, in these lines //**
lblChkCopyIMAge.Text = imgBarCode.ToString();
}
placehod.Controls.Add(imgBarCode);
}
Can please anyone assist me to save complete Barcode image in specific folder and respective URL in database so that I can use it further. The code written above is just generating barcode image and a long string URL. When I saved it in database it is saving this string in URL: "System.Web.UI.WebControls.Label". I have used nvarchar(max) datatype to save ImageURL.
My code to Save in database is mentioned below:
string strcmd5 = "update product set symbology=" + "'" + "IDAutomationHC39M" + "'" + "," + "barcodeimage=" + "'" + lblChkCopyIMAge + "'" + "where productId=" + int.Parse(Label1.Text);
SqlCommand objsqlcmd5 = new SqlCommand(strcmd5, objsqlcon4);
int h = objsqlcmd5.ExecuteNonQuery();
objsqlcon4.Close();
if (h > 0)
{
Response.Write("Record has submitted Successfully");
ScriptManager.RegisterStartupScript(this, this.GetType(), "barcode", "alert('Saved Successfully');", true);
}

You're setting the value to a label control:
"barcodeimage=" + "'" + lblChkCopyIMAge + "'"
As an object, the default string representation for a label control is the name of the type. You probably want to use its .Text property instead?
"barcodeimage=" + "'" + lblChkCopyIMAge.Text + "'"
Note that you should also really look into using parameterized queries for your database interaction. As it stands right now, any user input used in this query is a SQL injection vulnerability.

Related

Adding lines of text using PDFsharp

I am using PDFsharp to create PDF files. My problem is when I lay down the lines of text to the PDF I get a single line only. So naturally, all of the text that fits on a the first line is visible since the other text has overflowed out of bounds.
Please see my code below:
private void createPdf2()
{
var title = DateTime.Now.ToString("MM-dd-yyyy-hh-m-ss") + "-" + txtPlazaNumber.Text + "-" + txtLaneNumber.Text;
var now = DateTime.Now;
var sb = new StringBuilder();
sb.AppendLine("Date: " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss")).AppendLine(Environment.NewLine);
sb.AppendLine("Plaza Number: " + txtPlazaNumber.Text).AppendLine(Environment.NewLine);
sb.AppendLine("Lane Number: " + txtLaneNumber.Text).AppendLine(Environment.NewLine);
sb.AppendLine("RFID IP Address: " + txtRfidIpAddress.Text).AppendLine(Environment.NewLine);
sb.AppendLine("RFID Port: " + nRfidPort.Text).AppendLine(Environment.NewLine);
sb.AppendLine("TFI IP Address: " + txtTfiIpAddress.Text).AppendLine(Environment.NewLine);
sb.AppendLine("QR Port: " + nQrPort.Text).AppendLine(Environment.NewLine);
sb.AppendLine("Passed Tests").AppendLine();
foreach(var p in passedList)
{
sb.AppendLine("\t").Append(p.Trim()).AppendLine();
}
sb.AppendLine("Failed Tests").AppendLine();
foreach(var f in failedList)
{
sb.AppendLine("\f").Append(f.Trim()).AppendLine();
}
PdfDocument pdf = new PdfDocument();
pdf.Info.Title = title;
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 12, XFontStyle.Regular);
graph.DrawString(sb.ToString(), font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
string pdfFilename = title + ".pdf";
pdf.Save(pdfFilename);
}
This is a little bit trickier to work around. You need an XTextFormatter, a XRect for the region which is available for the layouter and then call DrawString(…) on the formatter instead of the XGraphics object:
var formatter = new XTextFormatter(pageGraphics);
var layoutRectangle = new XRect(10, 10, page.Width, page.Height);
formatter.DrawString("Hello\r\nWorld", arial, XBrushes.Black, layoutRectangle);
http://development.wellisolutions.de/generating-pdf-with-pdfsharp/

out of memory exception while drawing image in asp.net

We are drawing and editing pdf by using the following code,but when we play with 11mb size file,we are getting out of memory exception,can we fix the issue,I had used System.Drawing.Image.FromFile instead of FromStream but no luck..
public static string ImageCar()
{
string FileName = HttpContext.Current.Session["filename"].ToString();
Document doc = new Document(FileName);
ArrayList arrFiles = new ArrayList();
string strFileName = "";
for (int pageCount = 1; pageCount <= TotalPages; pageCount++)
{
using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image_" + strDateTime + "_" + pageCount + ".png"), FileMode.Create, FileAccess.ReadWrite))
{
strFileName = HttpContext.Current.Server.MapPath("Path" + strDateTime + "_" + pageCount + ".png");
arrFiles.Add(strFileName);
PngDevice pngDevice = new PngDevice();
//Convert a particular page and save the image to stream
pngDevice.Process(doc.Pages[pageCount], imageStream);
using (System.Drawing.Image image = System.Drawing.Image.FromStream(imageStream))
{
ScaleImage(image, 1189, 835, HttpContext.Current.Server.MapPath("Input/image1_" + strDateTime + "_" + pageCount + ".png"), out height, out Aratio);
image.Dispose();
imageStream.Close();
if (pageCount == 1)
fields = CheckFields(doc, pageCount, "image1_" + strDateTime + "_" + pageCount + ".png", fields, Convert.ToDouble(Aratio), licensed);
pages = pages + "," + "image1_" + strDateTime + "_" + pageCount + ".png";
Ratios = Ratios + "," + Aratio;
Allheights = Allheights + "," + height;
// Delete file from image folder
try
{
if (File.Exists(strFileName))
{
File.Delete(strFileName);
}
}
catch (Exception ex)
{
}
}
}
}
Ratios = Ratios.Substring(1, Ratios.Length - 1);
pages = pages.Substring(1, pages.Length - 1);
Allheights = Allheights.Substring(1, Allheights.Length - 1);
if (fields != "")
{
fields = fields.Substring(3, fields.Length - 3);
}
return pages + "%#" + Ratios + "%#" + Allheights + "%#" + fields;
}
System.Drawing has known memory leaks in a ASP site, and should never be used.
It will eventually case OOM errors, and while you can avoid it by restarting the server every so often, or throwing more memory at it, there is no real, long term fix. Use some other library for the image manipulation portion, and you should have less issues.
See the bottom of this page:
https://msdn.microsoft.com/en-us/library/system.drawing(v=vs.110).aspx
Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.

A generic error occurred in GDI+. at System.Drawing.Image.Save

Hi I am getting this error while saving an Image at the given path
string WriteImage(string data, string imgPath)
{
try
{
data = "*" + data + "*";
Bitmap barcode = new Bitmap(1, 1);
Font threeOfNine = new Font("IDAutomationHC39M", 60, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
Graphics graphics = Graphics.FromImage(barcode);
SizeF dataSize = graphics.MeasureString(data, threeOfNine);
barcode = new Bitmap(barcode, dataSize.ToSize());
graphics = Graphics.FromImage(barcode);
graphics.Clear(Color.White);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
graphics.DrawString(data, threeOfNine, new SolidBrush(Color.Black), 0, 0);
graphics.Flush();
threeOfNine.Dispose();
graphics.Dispose();
barcode.SetResolution(300, 300);
barcode.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
return imgPath.Substring(imgPath.LastIndexOf("\\")+1);
}
catch
{
return "";
}
}
Dont know what i am doing wrong.
As I wrote in my comment, I'm not seeing any problem. The following version of your code outputs information in the event of an error so you can debug it. It also disposes of resources properly:
public static string WriteImage(string data, string imgPath)
{
try
{
data = "*" + data + "*";
using (var dummyBitmap = new Bitmap(1, 1))
using (var threeOfNine = new Font("IDAutomationHC39M", 60, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point))
{
SizeF dataSize;
using (var graphics = Graphics.FromImage(dummyBitmap))
{
dataSize = graphics.MeasureString(data, threeOfNine);
}
using (var barcode = new Bitmap(dummyBitmap, dataSize.ToSize()))
using (var graphics = Graphics.FromImage(barcode))
using (var brush = new SolidBrush(Color.Black))
{
graphics.Clear(Color.White);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
graphics.DrawString(data, threeOfNine, brush, 0, 0);
graphics.Flush();
barcode.SetResolution(300, 300);
barcode.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
return imgPath.Substring(imgPath.LastIndexOf("\\") + 1);
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error saving string \"" + data + "\" to a bitmap at location: " + imgPath);
Debug.WriteLine(ex.ToString());
return "";
}
}

ShellTile.Create with FlipTileData throws InvalidOperationException?

I am trying to create a tile using FlipTileData in Windows Phone 8. I use this code:
const string mainPage = "/MainPage.xaml";
...
Uri mp = new Uri(mainPage + "?" + "tileid=" + tileId, UriKind.Relative);
FlipTileData tileData = new FlipTileData();
tileData.Title = tileTitle;
tileData.BackgroundImage = new Uri("isostore:" + isourl);
tileData.SmallBackgroundImage = new Uri("isostore:" + isourl);
tileData.WideBackgroundImage = new Uri("isostore:" + isourl);
ShellTile.Create(mp, tileData);
This throws an InvalidOperationException at the ShellTile.Create method. There are no other tiles with the same Navigation URI. What am I doing wrong here?
This code works fine using the StandardTileData class, excluding the SmallBackgroundImage and WideBackgroundImage properties.
If it matters, the full code is:
const string mainPage = "/MainPage.xaml";
...
private void createbutton_Click(object sender, RoutedEventArgs e)
{
string tileId = new Random().Next().ToString();
Uri mp = new Uri(mainPage + "?" + "tileid=" + tileId, UriKind.Relative);
WriteableBitmap wbmp = new WriteableBitmap(tileGrid, null);
string isourl = "/Shared/ShellContent/" + tileId + ".jpg";
IsolatedStorageFileStream isfs = IsolatedStorageFile.GetUserStoreForApplication().CreateFile(isourl);
wbmp.SaveJpeg(isfs, 173, 173, 0, 100);
isfs.Close();
FlipTileData tileData = new FlipTileData();
tileData.Title = tileTitle;
tileData.BackgroundImage = new Uri("isostore:" + isourl);
tileData.SmallBackgroundImage = new Uri("isostore:" + isourl);
tileData.WideBackgroundImage = new Uri("isostore:" + isourl);
ShellTile.Create(mp, tileData);
}
If using the new tile templates you need to use the overload of ShellTile.Create() that includes a third parameter.
This should do the trick:
ShellTile.Create(mp, tileData, true);
Are you calling this code inside the Closing handler?
In Windows Phone 8, creating a Tile by using the Create(Uri, ShellTileData) method inside the Closing handler will throw an InvalidOperationException.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206947(v=vs.105).aspx
edit: i guess not, since you said it worked with StandardTileData...

JPG to PDF Convertor in C#

I would like to convert from an image (like jpg or png) to PDF.
I've checked out ImageMagickNET, but it is far too complex for my needs.
What other .NET solutions or code are there for converting an image to a PDF?
Easy with iTextSharp:
class Program
{
static void Main(string[] args)
{
Document document = new Document();
using (var stream = new FileStream("test.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfWriter.GetInstance(document, stream);
document.Open();
using (var imageStream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var image = Image.GetInstance(imageStream);
document.Add(image);
}
document.Close();
}
}
}
iTextSharp does it pretty cleanly and is open source. Also, it has a very good accompanying book by the author which I recommend if you end up doing more interesting things like managing forms. For normal usage, there are plenty resources on mailing lists and newsgroups for samples of how to do common things.
EDIT: as alluded to in #Chirag's comment, #Darin's answer has code that definitely compiles with current versions.
Example usage:
public static void ImagesToPdf(string[] imagepaths, string pdfpath)
{
using(var doc = new iTextSharp.text.Document())
{
iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(pdfpath, FileMode.Create));
doc.Open();
foreach (var item in imagepaths)
{
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(item);
doc.Add(image);
}
}
}
Another working code, try it
public void ImagesToPdf(string[] imagepaths, string pdfpath)
{
iTextSharp.text.Rectangle pageSize = null;
using (var srcImage = new Bitmap(imagepaths[0].ToString()))
{
pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
}
using (var ms = new MemoryStream())
{
var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
document.Open();
var image = iTextSharp.text.Image.GetInstance(imagepaths[0].ToString());
document.Add(image);
document.Close();
File.WriteAllBytes(pdfpath+"cheque.pdf", ms.ToArray());
}
}
One we've had great luck with is PDFSharp (we use it for TIFF and Text to PDF conversion for hundreds of medical claims every day).
http://pdfsharp.com/PDFsharp/
Such task can be easily done with help of Docotic.Pdf library.
Here is a sample that creates PDF from given images (not only JPGs, actually):
public static void imagesToPdf(string[] images, string pdfName)
{
using (PdfDocument pdf = new PdfDocument())
{
for (int i = 0; i < images.Length; i++)
{
if (i > 0)
pdf.AddPage();
PdfPage page = pdf.Pages[i];
string imagePath = images[i];
PdfImage pdfImage = pdf.AddImage(imagePath);
page.Width = pdfImage.Width;
page.Height = pdfImage.Height;
page.Canvas.DrawImage(pdfImage, 0, 0);
}
pdf.Save(pdfName);
}
}
Disclaimer: I work for the vendor of the library.
If you want to do it in a cross-platform way, without any thirty part library,
or paying any license, you can use this code.
It takes an array of pictures (I think it only works only with jpg) with its sizes and return a pdf file, with one picture per page.
You have to create two files:
File Picture:
using System;
using System.Collections.Generic;
using System.Text;
namespace PDF
{
public class Picture
{
private byte[] data;
private int width;
private int height;
public byte[] Data { get => data; set => data = value; }
public int Width { get => width; set => width = value; }
public int Height { get => height; set => height = value; }
}
}
File PDFExport:
using System;
using System.Collections.Generic;
namespace PDF
{
public class PDFExport
{
private string company = "Your Company Here";
public sbyte[] createFile(List<Picture> pictures)
{
int N = (pictures.Count + 1) * 3;
string dateTimeStr = DateTime.Now.ToString("yyyyMMddhhmmss");
string file1 =
"%PDF-1.4\n";
string file2 =
"2 0 obj\n" +
"<<\n" +
"/Type /Pages\n" +
getKids(pictures) +
"/Count " + pictures.Count + "\n" +
">>\n" +
"endobj\n" +
"1 0 obj\n" +
"<<\n" +
"/Type /Catalog\n" +
"/Pages 2 0 R\n" +
"/PageMode /UseNone\n" +
"/PageLayout /SinglePage\n" +
"/Metadata 7 0 R\n" +
">>\n" +
"endobj\n" +
N + " 0 obj\n" +
"<<\n" +
"/Creator(" + company + ")\n" +
"/Producer(" + company + ")\n" +
"/CreationDate (D:" + dateTimeStr + ")\n" +
"/ModDate (D:" + dateTimeStr + ")\n" +
">>\n" +
"endobj\n" +
"xref\n" +
"0 " + (N + 1) + "\n" +
"0000000000 65535 f\n" +
"0000224088 00000 n\n" +
"0000224031 00000 n\n" +
"0000000015 00000 n\n" +
"0000222920 00000 n\n" +
"0000222815 00000 n\n" +
"0000224153 00000 n\n" +
"0000223050 00000 n\n" +
"trailer\n" +
"<<\n" +
"/Size " + (N + 1) + "\n" +
"/Root 1 0 R\n" +
"/Info 6 0 R\n" +
">>\n" +
"startxref\n" +
"0\n" +
"%% EOF";
sbyte[] part1 = file1.GetBytes();
sbyte[] part2 = file2.GetBytes();
List<sbyte[]> fileContents = new List<sbyte[]>();
fileContents.Add(part1);
for (int i = 0; i < pictures.Count; i++)
{
fileContents.Add(getPageFromImage(pictures[i], i));
}
fileContents.Add(part2);
return getFileContent(fileContents);
}
private string getKids(List<Picture> pictures)
{
string kids = "/Kids[";
for (int i = 0; i < pictures.Count; i++)
{
kids += (3 * (i + 1) + 1) + " 0 R ";
}
kids += "]\n";
return kids;
}
private sbyte[] getPageFromImage(Picture picture, int P)
{
int N = (P + 1) * 3;
string imageStart =
N + " 0 obj\n" +
"<<\n" +
"/Type /XObject\n" +
"/Subtype /Image\n" +
"/Width " + picture.Width + "\n" +
"/Height " + picture.Height + "\n" +
"/BitsPerComponent 8\n" +
"/ColorSpace /DeviceRGB\n" +
"/Filter /DCTDecode\n" +
"/Length " + picture.Data.Length + "\n" +
">>\n" +
"stream\n";
string dimentions = "q\n" +
picture.Width + " 0 0 " + picture.Height + " 0 0 cm\n" +
"/X0 Do\n" +
"Q\n";
string imageEnd =
"\nendstream\n" +
"endobj\n" +
(N + 2) + " 0 obj\n" +
"<<\n" +
"/Filter []\n" +
"/Length " + dimentions.Length + "\n" +
">>\n" +
"stream\n";
string page =
"\nendstream\n" +
"endobj\n" +
(N + 1) + " 0 obj\n" +
"<<\n" +
"/Type /Page\n" +
"/MediaBox[0 0 " + picture.Width + " " + picture.Height + "]\n" +
"/Resources <<\n" +
"/XObject <<\n" +
"/X0 " + N + " 0 R\n" +
">>\n" +
">>\n" +
"/Contents 5 0 R\n" +
"/Parent 2 0 R\n" +
">>\n" +
"endobj\n";
List<sbyte[]> fileContents = new List<sbyte[]>();
fileContents.Add(imageStart.GetBytes());
fileContents.Add(byteArrayToSbyteArray(picture.Data));
fileContents.Add(imageEnd.GetBytes());
fileContents.Add(dimentions.GetBytes());
fileContents.Add(page.GetBytes());
return getFileContent(fileContents);
}
private sbyte[] byteArrayToSbyteArray(byte[] data)
{
sbyte[] data2 = new sbyte[data.Length];
for (int i = 0; i < data2.Length; i++)
{
data2[i] = (sbyte)data[i];
}
return data2;
}
private sbyte[] getFileContent(List<sbyte[]> fileContents)
{
int fileSize = 0;
foreach (sbyte[] content in fileContents)
{
fileSize += content.Length;
}
sbyte[] finaleFile = new sbyte[fileSize];
int index = 0;
foreach (sbyte[] content in fileContents)
{
for (int i = 0; i < content.Length; i++)
{
finaleFile[index + i] = content[i];
}
index += content.Length;
}
return finaleFile;
}
}
}
You can use the code in this easy way
///////////////////////////////////////Export PDF//////////////////////////////////////
private sbyte[] exportPDF(List<Picture> images)
{
if (imageBytesList.Count > 0)
{
PDFExport pdfExport = new PDFExport();
sbyte[] fileData = pdfExport.createFile(images);
return fileData;
}
return null;
}
You need Acrobat to be installed. Tested on Acrobat DC. This is a VB.net code. Due to that these objects are COM objects, you shall do a 'release object', not just a '=Nothing". You can convert this code here: https://converter.telerik.com/
Private Function ImageToPDF(ByVal FilePath As String, ByVal DestinationFolder As String) As String
Const PDSaveCollectGarbage As Integer = 32
Const PDSaveLinearized As Integer = 4
Const PDSaveFull As Integer = 1
Dim PDFAVDoc As Object = Nothing
Dim PDFDoc As Object = Nothing
Try
'Check destination requirements
If Not DestinationFolder.EndsWith("\") Then DestinationFolder += "\"
If Not System.IO.Directory.Exists(DestinationFolder) Then Throw New Exception("Destination directory does not exist: " & DestinationFolder)
Dim CreatedFile As String = DestinationFolder & System.IO.Path.GetFileNameWithoutExtension(FilePath) & ".pdf"
'Avoid conflicts, therefore previous file there will be deleted
If File.Exists(CreatedFile) Then File.Delete(CreatedFile)
'Get PDF document
PDFAVDoc = GetPDFAVDoc(FilePath)
PDFDoc = PDFAVDoc.GetPDDoc
If Not PDFDoc.Save(PDSaveCollectGarbage Or PDSaveLinearized Or PDSaveFull, CreatedFile) Then Throw New Exception("PDF file cannot be saved: " & PDFDoc.GetFileName())
If Not PDFDoc.Close() Then Throw New Exception("PDF file could not be closed: " & PDFDoc.GetFileName())
PDFAVDoc.Close(1)
Return CreatedFile
Catch Ex As Exception
Throw Ex
Finally
System.Runtime.InteropServices.Marshal.ReleaseComObject(PDFDoc)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(PDFDoc)
PDFDoc = Nothing
System.Runtime.InteropServices.Marshal.ReleaseComObject(PDFAVDoc)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(PDFAVDoc)
PDFAVDoc = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
End Try
End Function
not sure if you're looking for just free / open source solutions or considering commercial ones as well. But if you're including commercial solutions, there's a toolkit called EasyPDF SDK that offers an API for converting images (plus a number of other file types) to PDF. It supports C# and can be found here:
http://www.pdfonline.com/
The C# code would look as follows:
Printer oPrinter = new Printer();
ImagePrintJob oPrintJob = oPrinter.ImagePrintJob;
oPrintJob.PrintOut(imageFile, pdfFile);
To be fully transparent, I should disclaim that I do work for the makers of EasyPDF SDK (hence my handle), so this suggestion is not without some personal bias :) But feel free to check out the eval version if you're interested. Cheers!
I use Sautinsoft, its very simple:
SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
p.Serial="xxx";
p.HtmlToPdfConvertStringToFile("<html><body><img src=\""+filename+"\"></img></body></html>","output.pdf");
You may try to convert any Images to PDF using this code sample:
PdfVision v = new PdfVision();
ImageToPdfOptions options = new ImageToPdfOptions();
options.JpegQuality = 95;
try
{
v.ConvertImageToPdf(new string[] {inpFile}, outFile, options);
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.ReadLine();
}
Or if you need to convert Image Class to PDF:
System.Drawing.Image image = Image.FromFile(#"..\..\image-jpeg.jpg");
string outFile = new FileInfo(#"Result.pdf").FullName;
PdfVision v = new PdfVision();
ImageToPdfOptions options = new ImageToPdfOptions();
options.PageSetup.PaperType = PaperType.Auto;
byte[] imgBytes = null;
using (MemoryStream ms = new System.IO.MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
imgBytes = ms.ToArray();
}
try
{
v.ConvertImageToPdf(imgBytes, outFile, options);
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.ReadLine();
}
Many diff tools out there. One I use is PrimoPDF (FREE) http://www.primopdf.com/ you go to print the file and you print it to pdf format onto your drive. works on Windows

Categories

Resources