שיכלול משמעותי לעבודה עם קבצי HTML וכן קבצי PDF ו Tiff בצורה חכמה
אם יש את נפש מאן דהו לבדוק את הקוד אם הוא נקי דיו, וכן להשלים את החסר המרה מקבצי PDF לקבצים אחרים (אני לא יודע לממש את זה ב ITEXTSHARP)
הנה הילד:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace FormatConvertor
{
class Convertor
{
/// <summary>
/// מחזיר את המחלקה המתאימה לקובץ על בסיס שמו של הקובץ
/// </summary>
/// <param name="FileName">שמו של הקובץ המלא עם הסיומת</param>
/// <returns>מחזיר אובייקט מסוג מתאים על פי הסיומת של הקובץ</returns>
private static ImageFormat GetImageFormat(string fileName)
{
string extension = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(extension))
throw new ArgumentException(
string.Format("לא היתה אפשרות לקבוע סיומת: {0}", fileName));
switch (extension.ToLower())
{
case @".bmp":
return ImageFormat.Bmp;
case @".gif":
return ImageFormat.Gif;
case @".ico":
return ImageFormat.Icon;
case @".jpg":
case @".jpeg":
return ImageFormat.Jpeg;
case @".png":
return ImageFormat.Png;
case @".tif":
case @".tiff":
return ImageFormat.Tiff;
case @".wmf":
return ImageFormat.Wmf;
default:
Application.Exit();
return ImageFormat.Wmf;
}
}
Bitmap GetBitmap(string fileName)
{
return new Bitmap(fileName);
}
/// <summary>
/// מבצע המרה פשוטה מפורמט לפורמט על בסיס הסיומת של קובץ המקור וקובץ היעד
/// </summary>
/// <param name="SourceFileName">שם מלא של קובץ המקור כולל נתיב</param>
/// <param name="TargetFileName"> שם מלא של קובץ היעד כולל נתיב</param>
/// <param name="DropSource">האם למחוק את קובץ המקור לאחר ההמרה אם הצליחה ברירת מחדל - לא</param>
/// <returns>אם ההמרה הצליחה מחזיר אמת ואם לא מחזיר שקר</returns>
public static bool ExecuteConvertingByNames(string SourceFileName, string TargetFileName, bool DropSource)
{
string TargetExtension = Path.GetExtension(TargetFileName).ToLower();
string SourceExtension = Path.GetExtension(SourceFileName).ToLower();
//בודק אם היעד הנוכחי נתמך בתוכנית שלנו
//source html
if (Path.GetExtension(SourceFileName).ToLower() == ".html")
{
return Html2(SourceFileName, TargetFileName, DropSource);
}
//tif to pdf
if ((SourceExtension == "tif" || SourceExtension == "tiff") && TargetExtension == "pdf")
{
bool result = Tiff2PDF(SourceFileName, TargetFileName);
if (result && DropSource)
{
File.Delete(SourceFileName);
}
return result;
}
//image to pdf
if (TargetExtension == "pdf")
{
return Bitmap2PDF(new Bitmap(SourceFileName), TargetFileName);
}
//pdf to tiff ot other is missing
if (SourceExtension == "pdf") //&& (TargetExtension == "tiff" || TargetExtension == "tif"))
{
return false;
}
//image to image
try
{
Bitmap btmp = new Bitmap(SourceFileName);
btmp.Save(TargetFileName, GetImageFormat(TargetFileName));
btmp.Dispose();
if (DropSource == true) { File.Delete(SourceFileName); }
return true;
}
catch (Exception e)
{
return false;
}
}
static bool Bitmap2PDF(Bitmap bmp, string TargetFileName)
{
try
{
Document doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, new FileStream(TargetFileName, FileMode.Create));
doc.Open();
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(bmp, System.Drawing.Imaging.ImageFormat.Jpeg);
doc.Add(pdfImage);
doc.Close();
return true;
}
catch (Exception)
{
return false;
}
}
static bool Html2(string htmlPath, string TargetFileName, bool DropSource)
{
string TargetExtension = Path.GetExtension(TargetFileName).ToLower();
//קובץ HTML המבקש המרה מקבל טיפול מיוחד
try
{
// אם רוצים להמיר לפידיאף מתבצעת המרה ישירה
if (TargetExtension == ".pdf" || TargetExtension == "tiff" || TargetExtension == "tif")
{
string TempTargetFileName = Path.Combine(Path.GetDirectoryName(TargetFileName), Path.GetFileNameWithoutExtension(TargetFileName) + ".pdf");
if (WkHtmlConvert(htmlPath, TempTargetFileName).EndsWith("done"))
{
// אם רוצים קובץ tiff ייתכן שיש צורך בריבוי עמודים ולכן נמיר תחילה ל PDF ולאחר מכן ל tiff
if (TargetExtension == "tiff" || TargetExtension == "tif")
{
bool result = ExecuteConvertingByNames(TempTargetFileName, TargetFileName, DropSource);
if (DropSource && result) { File.Delete(htmlPath); }
return result;
}
if (DropSource == true) { File.Delete(htmlPath); }
return true;
}
else
{
return false;
}
}
//המרה לפורמט אחר שאינו פידיאף
else
{
//במידה והפורמט נתמך באופן ישיר אפשר להשתמש ב wk
if (TargetExtension == ".jpg" || TargetExtension == ".jpeg" || TargetExtension == ".png" || TargetExtension == ".bmp")
{
if (WkHtmlConvert(htmlPath, TargetFileName, "image").EndsWith("done"))
{
if (DropSource == true) { File.Delete(htmlPath); }
return true;
}
}
//במידה והפורמט המבוקש אינו נתמך ישירות יש לבצע המרה כפולה
else
{
if (WkHtmlConvert(htmlPath, Path.Combine(Path.GetDirectoryName(TargetFileName), Path.GetFileNameWithoutExtension(TargetFileName) + ".bmp"), "image").EndsWith("done"))
{
if (DropSource == true) { File.Delete(htmlPath); }
//ממיר כעת לפורמט הרצוי
return ExecuteConvertingByNames(Path.Combine(Path.GetDirectoryName(TargetFileName), Path.GetFileNameWithoutExtension(TargetFileName) + ".bmp"), TargetFileName, DropSource);
}
}
}
return true;
}
catch (Exception e)
{
return false;
}
}
static string WkHtmlConvert(string HtmlPath, string TargetFileName, string TargetFiletype = "pdf")
{
//יש צורך להחזיר בתיקיית דיבאג או בין את הקבצים wkhtmltopdf.exe וכן wkhtmltoimage.exe
//אפשר להוריד מקור מכאן http://wkhtmltopdf.org/
//ראה כאן פרמטרים HTML ל PDF
//http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html
try
{
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo(Path.Combine(Directory.GetCurrentDirectory(), "wkhtmlto" + TargetFiletype + ".exe"),
" --zoom 1.35 " + // ב windows משום מה יש צורך בהגדלה של זום כדי שייצא כמו בן אדם
HtmlPath + " " + TargetFileName);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
//proc.WaitForExit();
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
return result;
}
catch (Exception e)
{
return e.Message;
}
}
static bool Tiff2PDF(string tifPath, string PDFPath)
{
if (Path.GetExtension(tifPath) == ".pdf")
{
File.Copy(tifPath, PDFPath);
return true;
}
try
{
// creation of the document with a certain size and certain margins
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
// creation of the different writers
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(PDFPath, System.IO.FileMode.Create));
// load the tiff image and count the total pages
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(tifPath);
int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
document.Open();
iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
for (int k = 0; k < total; ++k)
{
bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
// scale the image to fit in the page
img.ScalePercent(72f / img.DpiX * 100);
img.SetAbsolutePosition(0, 0);
cb.AddImage(img);
document.NewPage();
}
document.Close();
return true;
}
catch (Exception e)
{
return false;
}
}
}
}
פורסם במקור בפורום CODE613 ב17/01/2015 21:17 (+02:00)