Using C# and MediaInfo How to detect HDR format - c#

I'm using the MediaInfo Nuget Wrapper to analyse a bunch of files
using MediaInfo Actual on a file I can see
Video
ID : 1
Format : HEVC
Format/Info : High Efficiency Video Coding
Format profile : Main 10#L5.1#Main
HDR format : Dolby Vision, Version 1.0, dvhe.05.09, BL+RPU
Codec ID : dvhe
Codec ID/Info : High Efficiency Video Coding with Dolby Vision
This is also seen with Console.WriteLine(mw1.Inform());
However I'm unable to get that from the code below
I've tried HDR format, HDRformat and other speling but always returns ""
Given the fact that every file will be different is there a more dynamic way of doing this rather than hard coding each property?
Code still at testing stage
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MediaInfo;
using MediaInfo.Model;
namespace GetMediaInfo
{
class Program
{
static void Main(string[] args)
{
string BaseFold = #"Path\To\Test\Samples";
string[] Files = Directory.GetFiles(BaseFold, "*.*", SearchOption.AllDirectories);
foreach (var Vid in Files)
{
string VidName = Path.GetFileName(Vid);
if (VidName.EndsWith("jpg"))
{
continue;
}
Console.WriteLine(VidName);
var mw1 = new MediaInfo.MediaInfo();
mw1.Option("ParseSpeed", "0");
mw1.Open(Vid);
string ToDisplay = "";
var videostreamcount = mw1.CountGet(StreamKind.Video, 0);
var AudioStreamcount = mw1.CountGet(StreamKind.Audio, 0);
if (videostreamcount > 0)
{
Console.WriteLine(mw1.Inform());
foreach (var item in mw1.Get(StreamKind.Video,0,"*"))
{
Console.WriteLine(item);
}
var Height = mw1.Get(StreamKind.Video, 0, "Height");
var Width = mw1.Get(StreamKind.Video, 0, "Width");
var VidFormat = mw1.Get(StreamKind.Video, 0, "Format");
var HDRformat = mw1.Get(StreamKind.Video, 0, "HDR format"); // Always = ""
var Codec = mw1.Get(StreamKind.Video, 0, "CodecID/Info");
var CodecID = mw1.Get(StreamKind.Video, 0, "CodecID");
Console.WriteLine("Height " + Height + ", Width " + Width + ", Codec " + Codec + ", CodecID " + CodecID + ", Format " + VidFormat + " , HDR format " + HDRformat);
ToDisplay += "\r\n\r\nInfo_Parameters\r\n";
ToDisplay += mw1.Option("Info_Parameters");
//ToDisplay += "\r\n\r\nInfo_Capacities\r\n";
//ToDisplay += mw1.Option("Info_Capacities");
//ToDisplay += "\r\n\r\nInfo_Codecs\r\n";
//ToDisplay += mw1.Option("Info_Codecs");
// Console.WriteLine(ToDisplay);
}
else
{
Console.WriteLine("Error No video streams in file");
}
if (AudioStreamcount > 0)
{
var AudioCodec = mw1.Get(StreamKind.Audio, 0, "CodecID/Info");
var AudioCodecID = mw1.Get(StreamKind.Audio, 0, "CodecID");
var AudioFormat = mw1.Get(StreamKind.Audio, 0, "Format");
Console.WriteLine("AudioCodec: {0}, AudioCodecID: {1}, AudioFormat {2}", AudioCodec, AudioCodecID, AudioFormat);
}
else
{
Console.WriteLine("Error No Audio streams in file");
}
}
Console.ReadLine();
}
}
}
Thanx

I've tried HDR format, HDRformat and other speling but always returns ""
HDR_Format
Tip: for knowing the keys to use, use MediaInfo command line with " --Language=raw" or graphical interface with XML output.
Jérôme, developer of MediaInfo

Related

Convert PDF to TIFF using ImageMagick & C#

I have an existing program that does some processing a .pdf file and splitting it into multiple .pdf files based on looking for barcodes on the pages.
The program uses ImageMagick and C#.
I want to change it from outputting pdfs to outputting tifs. Look for the comment in the code below for where I would guess the change would be made.
I included the ImageMagick tag because someone might offer a commandline option that someone else can help me convert to C#.
private void BurstPdf(string bigPdfName, string targetfolder)
{
bool outputPdf = true; // change to false to output tif.
string outputExtension = "";
var settings = new MagickReadSettings { Density = new Density(200) };
string barcodePng = Path.Combine("C:\TEMP", "tmp.png");
using (MagickImageCollection pdfPageCollection = new MagickImageCollection())
{
pdfPageCollection.Read(bigPdfName, settings);
int inputPageCount = 0;
int outputPageCount = 0;
int outputFileCount = 0;
MagickImageCollection resultCollection = new MagickImageCollection();
string barcode = "";
string resultName = "";
IBarcodeReader reader = new BarcodeReader();
reader.Options.PossibleFormats = new List<BarcodeFormat>();
reader.Options.PossibleFormats.Add(BarcodeFormat.CODE_39);
reader.Options.TryHarder = false;
foreach (MagickImage pdfPage in pdfPageCollection)
{
MagickGeometry barcodeArea = getBarCodeArea(pdfPage);
IMagickImage barcodeImg = pdfPage.Clone();
barcodeImg.ColorType = ColorType.Bilevel;
barcodeImg.Depth = 1;
barcodeImg.Alpha(AlphaOption.Off);
barcodeImg.Crop(barcodeArea);
barcodeImg.Write(barcodePng);
inputPageCount++;
using (var barcodeBitmap = new Bitmap(barcodePng))
{
var result = reader.Decode(barcodeBitmap);
if (result != null)
{
// found a first page because it has bar code.
if (result.BarcodeFormat.ToString() == "CODE_39")
{
if (outputFileCount != 0)
{
// write out previous pages.
if (outputPdf) {
outputExtension = ".pdf";
} else {
// What do I put here to output a g4 compressed tif?
outputExtension = ".tif";
}
resultName = string.Format("{0:D4}", outputFileCount) + "-" + outputPageCount.ToString() + "-" + barcode + outputExtension;
resultCollection.Write(Path.Combine(targetfolder, resultName));
resultCollection = new MagickImageCollection();
}
barcode = standardizePhysicalBarCode(result.Text);
outputFileCount++;
resultCollection.Add(pdfPage);
outputPageCount = 1;
}
else
{
Console.WriteLine("WARNING barcode is not of type CODE_39 so something is wrong. check page " + inputPageCount + " of " + bigPdfName);
if (inputPageCount == 1)
{
throw new Exception("barcode not found on page 1. see " + barcodePng);
}
resultCollection.Add(pdfPage);
outputPageCount++;
}
}
else
{
if (inputPageCount == 1)
{
throw new Exception("barcode not found on page 1. see " + barcodePng);
}
resultCollection.Add(pdfPage);
outputPageCount++;
}
}
if (File.Exists(barcodePng))
{
File.Delete(barcodePng);
}
}
if (resultCollection.Count > 0)
{
if (outputPdf) {
outputExtension = ".pdf";
} else {
// What do I put here to output a g4 compressed tif?
outputExtension = ".tif";
}
resultName = string.Format("{0:D4}", outputFileCount) + "-" + outputPageCount.ToString() + "-" + barcode + outputExtension;
resultCollection.Write(Path.Combine(targetfolder, resultName));
outputFileCount++;
}
}
}
[EDIT] The above code is what I am using (which some untested modifications) to split a .pdf into other .pdfs. I want to know how to modify this code to output tiffs. I put a comment in the code where I think the change would go.
[EDIT] So encouraged by #fmw42 I just ran the code with the .tif extension enabled. Looks like it did convert to a .tif, but the tif is not compressed. I am surprised that IM just configures the output based on the extension name of the file. Handy I guess, but just seems a little loose.
[EDIT] I figured it out. Although counter-intuitive ones sets the compression on the read of the file. I am reading a .pdf but I set the compression to Group for like this:
var settings = new MagickReadSettings { Density = new Density(200), Compression = CompressionMethod.Group4 };
The thing I learned was that simply naming the output file .tif tells IM to output a tif. That is a handy way to do it, but it just seems sloppy.

C# compare id from text file in filestream

I need to fill a text file with information about workers. Then I need to read from the file and search for an ID that user tries to find. For example my file contains ids 1,2,3 and if I try to find id 3 and it matches, then this worker's all information is written in console. Otherwise it writes a text A worker cannot be found.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string file = "C:\\Temp\\registery.txt";
FileStream fOutStream = File.Open(file, FileMode.Append, FileAccess.Write);
StreamWriter sWriter = new StreamWriter(fOutStream);
int[] id = { 1, 2, 3 };
string[] name = { "John", "Carl", "Thomas" };
float[] salary = { 3500, 4800, 2100 };
for (int i = 0; i < id.Length; i++)
{
sWriter.WriteLine(id[i] + " " + name[i] + " " + salary[i]);
}
sWriter.Flush();
sWriter.Close();
FileStream fInStream = File.OpenRead(file);
StreamReader sReader = new StreamReader(fInStream);
int id2;
Console.WriteLine("Type worker's id");
id2 = int.Parse(Console.ReadLine());
bool a;
a = sReader.ReadToEnd().Contains(id2);
Console.WriteLine(a);
sReader.Close();
}
}
If you want to create a text file to be searchable, it should be delimited by a separator like comma /TAB
so modify your code:
sWriter.WriteLine(id[i] + "," + name[i] + "," + salary[i]);
To search your text file by id/name/..whatever and use AND/OR, you can use the method described here:
How would I convert data in a .txt file into xml? c#
BTW: Re-factor your code to create the file in a separate method, and the search in other one.
I found a solution myself to my problem and it worked good enough. It might not be the best solution. I removed bool things and I replaced the whole thing with this:
string line;
while ((line = sReader.ReadLine()) != null)
{
if (line.Contains("id: " + id2))
{
Console.WriteLine(line);
break;
}
else if ((line = sReader.ReadLine()) == null)
{
Console.WriteLine("Worker not found with id " + id2);
}
}
And I fixed the upper for loop to look like this:
sWriter.WriteLine("id: " + id[i] + " name: " + name[i] + " salary: " + salary[i]);

C# foreach string with commas

I have this code:
string[] neededFiles = {
"file1.exe",
"fille2.exe"
};
for (int file = 0; file != neededFiles.Length; file++)
{
if (!File.Exists(neededFiles[file]))
{
MessageBox.Show("App can't find this file - " + neededFiles[file]);
return;
}
}
Now when I launch my app it prints :
App can't find this file - file1.exe
App can't find this file - file2.exe
It's ok, but I wan't something like that:
App can't find this(-these) file(-files) - file1.exe, file2.exe
With what function / how can I do it? Is it possible? Thanks in advance
// using System.IO;
// using System.Windows.Forms;
// using System.Collections.Generics;
// using System.Linq;
IEnumerable<string> notFound = neededFiles.Where(f => !File.Exists(f));
if (notFound.Any())
MessageBox.Show(
string.Format(notFound.Count() > 1 ?
"App can't find these files - {0}" :
"App can't find this file - {0}",
string.Join(", ", notFound)));
Try this
string[] neededFiles = {
"file1.exe",
"fille2.exe"
};
string msg = string.Empty;
for (int file = 0; file != neededFiles.Length; file++)
{
if (!File.Exists(neededFiles[file]))
{
msg += neededFiles[file]+" ";
}
}
MessageBox.Show(" App can't find this(-these) file(-files) - " + msg);

Convert PDF to Image Batch

I am working on a solution where I can convert pdf files to images.
I am using the following example from codeproject:
http://www.codeproject.com/Articles/317700/Convert-a-PDF-into-a-series-of-images-using-Csharp?msg=4134859#xx4134859xx
now I tried with the following code to generate from more then 1000 pdf files new images:
using Cyotek.GhostScript;
using Cyotek.GhostScript.PdfConversion;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RefClass_PDF2Image
{
class Program
{
static void Main(string[] args)
{
string outputPath = Properties.Settings.Default.outputPath;
string pdfPath = Properties.Settings.Default.pdfPath;
if (!Directory.Exists(outputPath))
{
Console.WriteLine("Der angegebene Pfad " + outputPath + " für den Export wurde nicht gefunden. Bitte ändern Sie den Pfad (outputPath) in der App.Config Datei.");
return;
}
else
{
Console.WriteLine("Output Pfad: " + outputPath + " gefunden.");
}
if (!Directory.Exists(pdfPath))
{
Console.WriteLine("Der angegebene Pfad " + pdfPath + " zu den PDF Zeichnungen wurde nicht gefunden. Bitte ändern Sie den Pfad (pdfPath) in der App.Config Datei.");
return;
}
else
{
Console.WriteLine("PDF Pfad: " + pdfPath + " gefunden.");
}
Pdf2ImageSettings settings = GetPDFSettings();
DateTime start = DateTime.Now;
TimeSpan span;
Console.WriteLine("");
Console.WriteLine("Extraktion der PDF Zeichnungen wird gestartet: " + start.ToShortTimeString());
Console.WriteLine("");
DirectoryInfo diretoryInfo = new DirectoryInfo(pdfPath);
DirectoryInfo[] directories = diretoryInfo.GetDirectories();
Console.WriteLine("");
Console.WriteLine("Es wurden " + directories.Length + " verschiedende Verzeichnisse gefunden.");
Console.WriteLine("");
List<string> filenamesPDF = Directory.GetFiles(pdfPath, "*.pdf*", SearchOption.AllDirectories).Select(x => Path.GetFullPath(x)).ToList();
List<string> filenamesOutput = Directory.GetFiles(outputPath, "*.*", SearchOption.AllDirectories).Select(x => Path.GetFullPath(x)).ToList();
Console.WriteLine("");
Console.WriteLine("Es wurden " + filenamesPDF.Count + " verschiedende PDF Zeichnungen gefunden.");
Console.WriteLine("");
List<string> newFileNames = new List<string>();
int cutLength = pdfPath.Length;
for (int i = 0; i < filenamesPDF.Count; i++)
{
string temp = filenamesPDF[i].Remove(0, cutLength);
temp = outputPath + temp;
temp = temp.Replace("pdf", "jpg");
newFileNames.Add(temp);
}
for (int i = 0; i < filenamesPDF.Count; i++)
{
FileInfo fi = new FileInfo(newFileNames[i]);
if (!fi.Exists)
{
if (!Directory.Exists(fi.DirectoryName))
{
Directory.CreateDirectory(fi.DirectoryName);
}
Bitmap firstPage = new Pdf2Image(filenamesPDF[i], settings).GetImage();
firstPage.Save(newFileNames[i], System.Drawing.Imaging.ImageFormat.Jpeg);
firstPage.Dispose();
}
//if (i % 20 == 0)
//{
// GC.Collect();
// GC.WaitForPendingFinalizers();
//}
}
Console.ReadLine();
}
private static Pdf2ImageSettings GetPDFSettings()
{
Pdf2ImageSettings settings;
settings = new Pdf2ImageSettings();
settings.AntiAliasMode = AntiAliasMode.Medium;
settings.Dpi = 150;
settings.GridFitMode = GridFitMode.Topological;
settings.ImageFormat = ImageFormat.Png24;
settings.TrimMode = PdfTrimMode.CropBox;
return settings;
}
}
}
unfortunately, I always get in the Pdf2Image.cs an out of memory exception. here the code:
public Bitmap GetImage(int pageNumber)
{
Bitmap result;
string workFile;
//if (pageNumber < 1 || pageNumber > this.PageCount)
// throw new ArgumentException("Page number is out of bounds", "pageNumber");
if (pageNumber < 1)
throw new ArgumentException("Page number is out of bounds", "pageNumber");
workFile = Path.GetTempFileName();
try
{
this.ConvertPdfPageToImage(workFile, pageNumber);
using (FileStream stream = new FileStream(workFile, FileMode.Open, FileAccess.Read))
{
result = new Bitmap(stream); // --->>> here is the out of memory exception
stream.Close();
stream.Dispose();
}
}
finally
{
File.Delete(workFile);
}
return result;
}
how can I fix that to avoid this exception?
thanks for any help,
tro
Don't know if this is worth it for you, but it appears that you can do what you want without having a Bitmap in the middle. PdfToImage has this code in it:
public void ConvertPdfPageToImage(string outputFileName, int pageNumber)
{
if (pageNumber < 1 || pageNumber > this.PageCount)
throw new ArgumentException("Page number is out of bounds", "pageNumber");
using (GhostScriptAPI api = new GhostScriptAPI())
api.Execute(this.GetConversionArguments(this._pdfFileName, outputFileName, pageNumber, this.PdfPassword, this.Settings));
}
which writes a file for you where you want it. Why not just call that method directly instead of reading the image back in and writing it back out?
This might not be answering your question directly, but could still be useful: Imagemagick provides a simple way of creating images from pdfs in batch mode
Single pdf file to many jogs:
convert -geometry 1024x768 -density 200 -colorspace RGB test.pdf +adjoin test_%0d.jpg
or if you want to process many pdf files:
mogrify -format jpg -alpha off -density 150 -quality 80 -resize 768 -unsharp 1.5 *.pdf
(The settings should obviously be adapted to your needs :) )
To do this programmatically in C# you could use the .NET imagemagick wrapper
http://imagemagick.codeplex.com
Add using for your resulted bitmap
using (FileStream stream = new FileStream(workFile, FileMode.Open, FileAccess.Read))
using (Bitmap result = new Bitmap(stream))
{
...
}

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