Exception when creating new XFont. PDFSharp Xamarin - c#

When i debugging my app I got Exception when creating object of XFont. Any idea what is wrong?
In all examples I found on github etc. it was exactly like in this code below.
System.TypeInitializationException: 'The type initializer for
'PdfSharpCore.Utils.FontResolver' threw an exception.'
document.Info.Title = "created with pdfsharp";
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
// Draw the text
gfx.DrawString("Test of PdfSharp on Android", font,
new XSolidBrush(XColor.FromArgb(0, 0, 0)),
10, 130);
// Save the document...
document.Save(Path.Combine(Path.GetTempPath(), Name));

According to your code, I guess that you use PdfSharp.Xamarin.Forms library, now you want to use custom fonts for pdf, am I right?
if yes, please take a look the following code, implementing IFontResolver.
internal class FontProvider : IFontResolver
{
#region Properties
public string DefaultFontName
{
get { return "OpenSans"; }
}
#endregion
#region Fields
public ICustomFontProvider _fontProvider;
public static readonly string[] DefaultFontFiles = new string[]
{
"OpenSans-Regular.ttf",
"OpenSans-Bold.ttf",
"OpenSans-Italic.ttf",
"OpenSans-BoldItalic.ttf",
};
#endregion
#region Ctor
public FontProvider(ICustomFontProvider fontProvider)
{
_fontProvider = fontProvider;
}
#endregion
#region IFontResolver implementation
public byte[] GetFont(string faceName)
{
if (DefaultFontFiles.Contains(faceName) || _fontProvider == null)
{
var assembly = typeof(FontProvider).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"PdfSharp.Xamarin.Forms.DefaultFonts.{faceName}");
using (var reader = new StreamReader(stream))
{
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
return bytes;
}
}
else
{
return _fontProvider.GetFont(faceName);
}
}
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
{
string fontName;
if (familyName == DefaultFontName || _fontProvider == null)
fontName = DefaultFontFiles[Convert.ToInt32(isBold) + 2 * Convert.ToInt32(isItalic)];
else
fontName = _fontProvider.ProvideFont(familyName, isBold, isItalic);
return new FontResolverInfo(fontName);
}
#endregion
}
You can also write my own implementation of IFontResolver and assigning it to GlobalFontSettings.FontResolver.
Please take a look the following thread:
Loading a Font with PdfSharp .Net Standard preview from Xamarin.Forms fails: No appropriate font found

Related

IText7 PDFHtml generator with header and footer for C#

I am trying to generating a PDF from predefined HTML content. I managed to generate the content, yet without the required HTML Header, HTML Footer, and Arabic language is not supported as well.
My requirements:
Arabic language support.
The ability to generate more than 10 pages.
The footer may differ from one page to another.
There is a web application that sends a request to a WCF service, and the service returns a byte array containing the PDF.
So, I have been searching for a couple of days for a good tool and I found SelectPdf, it is perfect except that it is NOT free, so the only solution is IText7 PDFHtml.
The thing is this library has good documentation for JAVA, and I am really struggling in following the C# examples and converting from JAVA API to C# code.
Anyone has done something similar before with c#?
After a long process of searching and trying, I have got it working and achieved the following features:
Image in the header.
Base64 image in the footer, in addition to the ability to write some text in the other side in the footer.
Generating the same footer for all pages except for the last one.
the number of the generated pages was unlimited.
Page numbering.
All the previous features were free of charge, however, supporting Arabic language needs a license, so I have to pay anyway :)
Kindly find below my C# code and post your improvements if you have any.
public class Pdfgenerator
{
public const string FONT = "Fonts/NotoNaskhArabic-Regular2.ttf";
public static string HEADER_TEXT = "<table width=\"100%\" border=\"0\"><tr><td>Header</td><td align=\"right\">Some title</td></tr></table>";
public static string FOOTER_TEXT = "<table width=\"100%\" border=\"0\"><tr><td>Footer</td><td align=\"right\">Some title</td></tr></table>";
public MemoryStream createPdf()
{
string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
MemoryStream file = new MemoryStream();
PdfDocument pdfDocument = null;
PdfDocument pdfDoc = null;
PdfDocument pdfDocument1 = null;
try
{
using (file)
{
PdfFont f = PdfFontFactory.CreateFont(apPath + FONT, PdfEncodings.IDENTITY_H);
string header = "pdfHtml Header and footer example using page-events";
Header headerHandler = new Header(header);
Footer footerHandler = new Footer();
ConverterProperties converterProperties = new ConverterProperties();
PdfWriter writer1 = new PdfWriter(apPath + "test1.pdf");
pdfDocument1 = new PdfDocument(writer1);
pdfDocument1.AddEventHandler(PdfDocumentEvent.START_PAGE, headerHandler);
pdfDocument1.AddEventHandler(PdfDocumentEvent.END_PAGE, footerHandler);
converterProperties = new ConverterProperties().SetBaseUri(apPath);
HtmlConverter.ConvertToDocument(File.ReadAllText(apPath + "content.html"), pdfDocument1, converterProperties);
footerHandler.lastPage = pdfDocument1.GetLastPage();
pdfDocument1.Close();
}
}
catch (Exception ex)
{
}
finally
{
file.Dispose();
}
return new MemoryStream();
}
}
Generating the header:
class Header : IEventHandler
{
private string header;
private Image image;
public Header(string header)
{
string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
this.header = header;
image = new Image(ImageDataFactory.Create(apPath + "Images/RANDOM_PHOTO.jpg"));
}
public void HandleEvent(Event #event)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)#event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
Rectangle pageSize = page.GetPageSize();
Canvas canvas = new Canvas(new PdfCanvas(page), pdf, pageSize);
canvas.SetFontSize(18);
// Write text at position
canvas.Add(image);
canvas.Close();
}
}
Generating the footer:
class Footer : IEventHandler
{
public PdfPage lastPage = null;
protected PdfFormXObject placeholder;
protected float side = 20;
protected float x = 300;
protected float y = 25;
protected float space = 4.5f;
protected float descent = 3;
public Footer()
{
placeholder = new PdfFormXObject(new Rectangle(0, 0, side, side));
}
public void HandleEvent(Event #event)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)#event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdf.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
// Creates drawing canvas
PdfCanvas pdfCanvas = new PdfCanvas(page);
Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
IList<iText.Layout.Element.IElement> elements = HtmlConverter.ConvertToElements("<table border=\"0\"><tr><td><img src=\"data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==\" alt=\"Italian Trulli\"></td></tr></table>");
Paragraph p = new Paragraph();
foreach (iText.Layout.Element.IElement e in elements)
{
if (e is IBlockElement) {
p.Add((IBlockElement)e);
}
}
if (lastPage == docEvent.GetPage()) {
}
else
{
canvas.ShowTextAligned(p, 25, 75, TextAlignment.LEFT);
}
canvas.Close();
// Create placeholder object to write number of pages
pdfCanvas.AddXObject(placeholder, x + space, y - descent);
pdfCanvas.Release();
}
public void writeTotal(PdfDocument pdf)
{
Canvas canvas = new Canvas(placeholder, pdf);
canvas.ShowTextAligned(pdf.GetNumberOfPages().ToString(),
0, descent, TextAlignment.LEFT);
canvas.Close();
}
}
I was trying to get a stream as an output, so if you want that as well you can use the following in your main service:
public byte[] GetData()
{
MemoryStream stream = new Pdfgenerator().createPdf();
byte[] arr = stream.ToArray();
return stream.ToArray();
}

C# Pdf to Text with image placeholder

I have a batch of PDFs that I want to convert to Text. It's easy to get text with something like this from iTextSharp:
PdfTextExtractor.GetTextFromPage(reader, pageNumber);
It's easy to get Images using this answer (or similar answers in the thread).
What I can't figure out easily... is how to interleave image placeholders in the text.
Given a PDF, a page # and GetTextFromPage I expect the output to be:
line 1
line 2
line 3
When I'd like it to be (Where 1.1 means page 1, image 1... Page 1, image 2):
line 1
[1.1]
line 2
[1.2]
line 3
Is there a way to get an "image placeholder" for iTextSharp, PdfSharp or anything similar? I'd like a GetTextAndPlaceHoldersFromPage method (or similar).
PS: Hrm... it's not letting me tag iTextSHARP - not iText. C# not Java.
C# Pdf to Text with image placeholder
https://stackoverflow.com/a/28087521/
https://stackoverflow.com/a/33697745/
Although this doesn't have the exact layout mentioned in my question (Since that was a simplified version of what I really wanted anyways), it does have the starting parts as listed by the second note (translated from iText Java)... with extra information pulled from the third note (Some of the reflection used in Java didn't seem to work in C#, so that info came from #3).
Working from this, I'm able to get a List of Strings representing lines in the PDF (all pages, instead of just page 1)... with text added where images should be (Huzzah!). ByteArrayToFile extension method added for flavor (Although I didn't include other parts/extensions that may break a copy/paste usages of this code).
I've also been able to greatly simplify other parts of my process and gut half of the garbage I had working before. Huzzah!!! Thanks #Mkl
internal class Program
{
public static void Main(string[] args)
{
var dir = Settings.TestDirectory;
var file = Settings.TestFile;
Log.Info($"File to Process: {file.FullName}");
using (var reader = new PdfReader(file.FullName))
{
var parser = new PdfReaderContentParser(reader);
var listener = new SimpleMixedExtractionStrategy(file, dir);
parser.ProcessContent(1, listener);
var x = listener.GetResultantText().Split('\n');
}
}
}
public class SimpleMixedExtractionStrategy : LocationTextExtractionStrategy
{
public static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public DirectoryInfo OutputPath { get; }
public FileInfo OutputFile { get; }
private static readonly LineSegment UNIT_LINE = new LineSegment(new Vector(0, 0, 1), new Vector(1, 0, 1));
private int _counter;
public SimpleMixedExtractionStrategy(FileInfo outputFile, DirectoryInfo outputPath)
{
OutputPath = outputPath;
OutputFile = outputFile;
}
public override void RenderImage(ImageRenderInfo renderInfo)
{
try
{
var image = renderInfo.GetImage();
if (image == null) return;
var number = _counter++;
var imageFile = new FileInfo($"{OutputFile.FullName}-{number}.{image.GetFileType()}");
imageFile.ByteArrayToFile(image.GetImageAsBytes());
var segment = UNIT_LINE.TransformBy(renderInfo.GetImageCTM());
var location = new TextChunk("[" + imageFile + "]", segment.GetStartPoint(), segment.GetEndPoint(), 0f);
var locationalResultField = typeof(LocationTextExtractionStrategy).GetField("locationalResult", BindingFlags.NonPublic | BindingFlags.Instance);
var LocationalResults = (List<TextChunk>)locationalResultField.GetValue(this);
LocationalResults.Add(location);
}
catch (Exception ex)
{
Log.Debug($"{ex.Message}");
Log.Verbose($"{ex.StackTrace}");
}
}
}
public static class ByteArrayExtensions
{
public static bool ByteArrayToFile(this FileInfo fileName, byte[] byteArray)
{
try
{
// Open file for reading
var fileStream = new FileStream(fileName.FullName, FileMode.Create, FileAccess.Write);
// Writes a block of bytes to this stream using data from a byte array.
fileStream.Write(byteArray, 0, byteArray.Length);
// close file stream
fileStream.Close();
return true;
}
catch (Exception exception)
{
// Error
Log.Error($"Exception caught in process: {exception.Message}", exception);
}
// error occured, return false
return false;
}
}

Passing in a HttpPostedFileWrapper variable to a function breaks another function. Image validation and conversion in C#

So basically this part of the program is editing/uploading a new profile picture to a user's account. Previously, it worked fine. Then I decided to add in some picture validations (picture has to have certain dimensions, etc). So I made a separate Helper class for that that takes in the HttpPostedFileWrapper variable initialized in the controller.
So, in this controller function, I initialize a new instance of the ValidateImage class which holds two functions (DoValidation and Resize).
The Resize function was working fine until I added the DoValidation function and I feel like it has something to do with the memory stream.
I now get an "Invalid Parameter" error in the ResizeImage function (see below), even though I never changed that code and was working fine previously. Does it have something to do with the filestream not being closed properly or something?
Here is the code:
//Controller.cs
public virtual ActionResult EditMyProfilePicture(bool? ignore)
{
var loggedInEmployee = this.EmployeeRepos.GetEmployeeByUserName(User.Identity.Name);
int tgtWidth = 250, tgtHeight = 250;
try
{
// get a reference to the posted file
var file = Request.Files["FileContent"] as HttpPostedFileWrapper;
ValidateImage img = new ValidateImage();
if (file != null && file.ContentLength > 0)
{
// isolate the filename - IE returns full local path, other browsers: just the file name.
int index = file.FileName.LastIndexOf("\\");
// if not IE, index will be -1, but -1 + 1 = 0 so we are okay.
string fileName = file.FileName.Substring(index + 1);
// Validate the image
img.DoValidation(file, tgtWidth, tgtHeight);
if (!img.IsValidated)
{
throw new ArgumentException(img.Message);
}
else
{
byte[] resizedImg = img.Resize(file, tgtWidth, tgtHeight);
this.EmployeeRepos.SaveProfileImage(loggedInEmployee.EmployeeCode, resizedImg);
}
return RedirectToAction(MVC.Employees.EditMyProfile());
}
else
{
throw new ArgumentException("Please select a file to upload.");
}
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
}
return View(Views.EditMyProfilePicture, loggedInEmployee);
}
// ValidateImage.cs
public class ValidateImage
{
public string Message { get; private set; }
public bool IsValidated { get; private set; }
public void DoValidation(HttpPostedFileWrapper file, int tgtWidth, int tgtHeight)
{
try
{
Image img = Image.FromStream(file.InputStream);
int curHeight = img.Height, curWidth = img.Width;
// check for image too small
if (curHeight < tgtHeight || curWidth < tgtWidth)
{
Message = "image is too small. please upload a picture at least 250x250.";
IsValidated = false;
return;
}
// check for image is square
else if (curHeight != curWidth)
{
Message = "image is not a square.";
IsValidated = false;
return;
}
else
{
IsValidated = true;
}
}
catch
{
}
}
public byte[] Resize(HttpPostedFileWrapper file, int tgtWidth, int tgtHeight)
{
byte[] bytes = new byte[file.ContentLength];
file.InputStream.Read(bytes, 0, file.ContentLength);
file.InputStream.Close(); // close the file stream.
// Down-sample if needed from current byte array to max 250x250 Jpeg
byte[] resized = Helpers.ImageResizer.ResizeImage(bytes, tgtWidth, tgtHeight, ResizeOptions.MaxWidthAndHeight, ImageFormat.Jpeg);
return resized;
}
}
// Resize Image function
public static byte[] ResizeImage(byte[] bytes, int width, int height, ResizeOptions resizeOptions, ImageFormat imageFormat)
{
using (MemoryStream ms = new MemoryStream(bytes))
{
Image img = Image.FromStream(ms);
Bitmap bmp = new Bitmap(img);
bmp = ResizeImage(bmp, width, height, resizeOptions);
bmp.SetResolution(72, 72);
bmp.Save(ms, imageFormat);
return ms.ToArray();
}
}

Write metadata to both jpg and png

I need to add a metadata tag (description) to uploaded images.
I have found out this answer: https://stackoverflow.com/a/1764913/6776 which works great for JPG files, but not for PNG.
private string Tag = "test meta data";
private static Stream TagImage(Stream input, string type)
{
bool isJpg = type.EndsWith("jpg", StringComparison.InvariantCultureIgnoreCase) || type.EndsWith("jpeg", StringComparison.InvariantCultureIgnoreCase);
bool isPng = type.EndsWith("png", StringComparison.InvariantCultureIgnoreCase);
BitmapDecoder decoder = null;
if (isJpg)
{
decoder = new JpegBitmapDecoder(input, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
}
else if (isPng)
{
decoder = new PngBitmapDecoder(input, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
}
else
{
return input;
}
// modify the metadata
BitmapFrame bitmapFrame = decoder.Frames[0];
BitmapMetadata metaData = (BitmapMetadata)bitmapFrame.Metadata.Clone();
metaData.Subject = Tag;
metaData.Comment = Tag;
metaData.Title = Tag;
// get an encoder to create a new jpg file with the new metadata.
BitmapEncoder encoder = null;
if (isJpg)
{
encoder = new JpegBitmapEncoder();
}
else if (isPng)
{
encoder = new PngBitmapEncoder();
}
encoder.Frames.Add(BitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metaData, bitmapFrame.ColorContexts));
// Save the new image
Stream output = new MemoryStream();
encoder.Save(output);
output.Seek(0, SeekOrigin.Begin);
return output;
}
It works great when I upload a jpg, but with a png, at the metaData.Subject = Tag line, it throws a System.NotSupportedException (this codec does not support the specified property).
Update
It seems I have to use a different method based on the image format:
if (isJpg)
{
metaData.SetQuery("/app1/ifd/exif:{uint=270}", Tag);
}
else
{
metaData.SetQuery("/tEXt/{str=Description}", Tag);
}
Based on the available formats' queries the first should work for both formats. The second doesn't really work either (it creates the metadata in the image but does not save its value).
If I try to use the first method (/app1/ifd/exif) for PNG, at the encoder.Save line I get a not supported exception, "no imaging component suitable".
I solved it using pngcs library (you need to rename the downloaded dll to "pngcs.dll")
Here is how I implemented it:
using Hjg.Pngcs; // https://code.google.com/p/pngcs/
using Hjg.Pngcs.Chunks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MarkerGenerator.Utils
{
class PngUtils
{
public string getMetadata(string file, string key)
{
PngReader pngr = FileHelper.CreatePngReader(file);
//pngr.MaxTotalBytesRead = 1024 * 1024 * 1024L * 3; // 3Gb!
//pngr.ReadSkippingAllRows();
string data = pngr.GetMetadata().GetTxtForKey(key);
pngr.End();
return data; ;
}
public static void addMetadata(String origFilename, Dictionary<string, string> data)
{
String destFilename = "tmp.png";
PngReader pngr = FileHelper.CreatePngReader(origFilename); // or you can use the constructor
PngWriter pngw = FileHelper.CreatePngWriter(destFilename, pngr.ImgInfo, true); // idem
//Console.WriteLine(pngr.ToString()); // just information
int chunkBehav = ChunkCopyBehaviour.COPY_ALL_SAFE; // tell to copy all 'safe' chunks
pngw.CopyChunksFirst(pngr, chunkBehav); // copy some metadata from reader
foreach (string key in data.Keys)
{
PngChunk chunk = pngw.GetMetadata().SetText(key, data[key]);
chunk.Priority = true;
}
int channels = pngr.ImgInfo.Channels;
if (channels < 3)
throw new Exception("This example works only with RGB/RGBA images");
for (int row = 0; row < pngr.ImgInfo.Rows; row++)
{
ImageLine l1 = pngr.ReadRowInt(row); // format: RGBRGB... or RGBARGBA...
pngw.WriteRow(l1, row);
}
pngw.CopyChunksLast(pngr, chunkBehav); // metadata after the image pixels? can happen
pngw.End(); // dont forget this
pngr.End();
File.Delete(origFilename);
File.Move(destFilename, origFilename);
}
public static void addMetadata(String origFilename,string key,string value)
{
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add(key, value);
addMetadata(origFilename, data);
}
}
}
The library CompactExifLib can write EXIF tags in JPEG, TIFF and PNG files:
https://www.codeproject.com/Articles/5251929/CompactExifLib-Access-to-EXIF-Tags-in-JPEG-TIFF-an
It is written purely in C# and can be used for free.
Note: I am the author of this library.
The PNG-format does not support metadata :(
But XMP does, which might be of help when converting between JPEGs, with EXIF-metadata, and PNG.

Programmatically convert Word (docx) to PDF

Ok before you think "Not another question like this" please read this first.
I have an application (web application in ASP.NET MVC 3) the generates Word files in DocX using the DocX library.
The application takes a template and fills it in with all the data from a database.
Now I want to create a PDF version of that created docx-file.
I know apose.word is an option, but not for me since I have little budget. Other libs where I have to spend some money on are also out of the question.
I don't have a sharepoint server so Word Automation Services isn't an option either.
So I have 2 options (that I know) left and they both use iTextSharp. Don't know which is better.
I could use the generated XML from the docx file and transform it to a version that is usable by iTextSharp.
I could create the PDF like I create the docx with a template.
Anybody has any idea on how much work it is, which of those 2 has better performance and if it is even possible to do.
I know that the second option has the downside that when I change a template I have to change it for both versions.
If you have a better solution (free that is), you are welcome to share it.
Another option, even if it needs some work: install OpenOffice on server and, using UNO libraries (including them as assemblies in your app), you can open docx document and save it in PDF directly.
In a few minutes I post an example...
PARTIAL EXAMPLE:
This is a class I created a long time ago and used to convert files to pdf
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.container;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.view;
using System.Collections.Generic;
using System.IO;
namespace QOpenOffice
{
public enum AppType
{
Writer,
Calc,
Impress,
Draw,
Math
}
public enum ExportFilter{
Word97,
WriterPDF,
CalcPDF,
DrawPDF,
ImpressPDF,
MathPDF
}
class OpenOffice
{
private XComponentContext context;
private XMultiServiceFactory service;
private XComponentLoader component;
private XComponent doc;
private List<string> filters = new List<string>();
#region Constructors
public OpenOffice()
{
/// This will start a new instance of OpenOffice.org if it is not running,
/// or it will obtain an existing instance if it is already open.
context = uno.util.Bootstrap.bootstrap();
/// The next step is to create a new OpenOffice.org service manager
service = (XMultiServiceFactory)context.getServiceManager();
/// Create a new Desktop instance using our service manager
component = (XComponentLoader)service.createInstance("com.sun.star.frame.Desktop");
// Getting filters
XNameContainer filters = (XNameContainer)service.createInstance("com.sun.star.document.FilterFactory");
foreach (string filter in filters.getElementNames())
this.filters.Add(filter);
}
~OpenOffice()
{
if (doc != null)
doc.dispose();
doc = null;
}
#endregion
#region Private methods
private string FilterToString(ExportFilter filter)
{
switch (filter)
{
case ExportFilter.Word97: return "MS Word 97";
case ExportFilter.WriterPDF: return "writer_pdf_Export";
case ExportFilter.CalcPDF: return "calc_pdf_Export";
case ExportFilter.DrawPDF: return "draw_pdf_Export";
case ExportFilter.ImpressPDF: return "impress_pdf_Export";
case ExportFilter.MathPDF: return "math_pdf_Export";
}
return "";
}
#endregion
#region Public methods
public bool Load(string filename, bool hidden)
{
return Load(filename, hidden, "", "");
}
public bool Load(string filename, bool hidden, int filter_index, string filter_options)
{
return Load(filename, hidden, filters[filter_index], filter_options);
}
public bool Load(string filename, bool hidden, string filter_name, string filter_options)
{
List<PropertyValue> pv = new List<PropertyValue>();
pv.Add(new PropertyValue("Hidden", 0, new uno.Any(hidden), PropertyState.DIRECT_VALUE));
if (filter_name != "")
{
pv.Add(new PropertyValue("FilterName", 0, new uno.Any(filter_name), PropertyState.DIRECT_VALUE));
pv.Add(new PropertyValue("FilterOptions", 0, new uno.Any(filter_options), PropertyState.DIRECT_VALUE));
}
try
{
doc = component.loadComponentFromURL(
"file:///" + filename.Replace('\\', '/'), "_blank",
0, pv.ToArray());
return true;
}
catch
{
doc = null;
return false;
}
}
public bool Print()
{
return Print(1, "");
}
public bool Print(int copies, string pages)
{
List<PropertyValue> pv = new List<PropertyValue>();
pv.Add(new PropertyValue("CopyCount", 0, new uno.Any(copies), PropertyState.DIRECT_VALUE));
if (pages != "")
pv.Add(new PropertyValue("Pages", 0, new uno.Any(pages), PropertyState.DIRECT_VALUE));
//if (doc is XPrintable)
try
{
((XPrintable)doc).print(pv.ToArray());
return true;
}
catch { return false; }
}
public bool Save(string filename, ExportFilter filter)
{
return Save(filename, FilterToString(filter));
}
public bool Save(string filename, string filter)
{
List<PropertyValue> pv = new List<PropertyValue>();
pv.Add(new PropertyValue("FilterName", 0, new uno.Any(filter), PropertyState.DIRECT_VALUE));
pv.Add(new PropertyValue("Overwrite", 0, new uno.Any(true), PropertyState.DIRECT_VALUE));
try
{
filename = filename.Replace("\\", "/");
((XStorable)doc).storeToURL("file:///" + filename, pv.ToArray());
return true;
}
catch { return false; }
}
public bool ExportToPdf(string filename)
{
filename = Path.ChangeExtension(filename, ".pdf");
bool ret = Save(filename, "writer_pdf_Export");
if (!ret) ret = Save(filename, "impress_pdf_Export");
if (!ret) ret = Save(filename, "calc_pdf_Export");
if (!ret) ret = Save(filename, "draw_pdf_Export");
if (!ret) ret = Save(filename, "impress_pdf_Export");
if (!ret) ret = Save(filename, "math_pdf_Export");
return ret;
}
public void Close()
{
doc.dispose();
doc = null;
}
public bool New(AppType app, bool hidden)
{
try
{
string sapp = "private:factory/";
switch (app)
{
case AppType.Writer:
sapp += "swriter";
break;
case AppType.Calc:
sapp += "scalc";
break;
case AppType.Impress:
sapp += "simpress";
break;
case AppType.Draw:
sapp += "sdraw";
break;
case AppType.Math:
sapp += "smath";
break;
}
PropertyValue pv = new PropertyValue("Hidden", 0, new uno.Any(hidden), PropertyState.DIRECT_VALUE);
doc = component.loadComponentFromURL(sapp, "_blank", 0, new PropertyValue[1] { pv });
return true;
}
catch
{
doc = null;
return false;
}
}
#endregion
#region Properties
public List<string> Filters
{
get { return filters; }
}
#endregion
}
}

Categories

Resources