Converting docx to images using Aspose.Words - asp.net-mvc

I'm converting a generated doc to a pdf and to png's, see the code below. But for some reason there is something wrong with the fonts. On my local develop machine everything is right, but when deployed on the production servers the fonts in the PNG's are missing. I've checked but they are installed on the servers. Can someone help me with this?
var dstDoc = doc.Clone();
var newInvoice = new InvoicePdf(factuur);
var ds = newInvoice.ToDataSet();
dstDoc.BuiltInDocumentProperties.Title = newInvoice.InvoiceID;
dstDoc.BuiltInDocumentProperties.Subject = newInvoice.SendDate;
dstDoc.MailMerge.FieldMergingCallback = new HandleMergeFieldAlternatingRows();
dstDoc.MailMerge.ExecuteWithRegions(ds);
var filePath = Path.Combine(folderInvoices, newInvoice.SendDateOrginal.Year.ToString(CultureInfo.InvariantCulture));
Directory.CreateDirectory(filePath);
var fileName = string.Format("{0} - {1}", newInvoice.InvoiceID, newInvoice.DebtorCompany.ToString(true));
filePath = Path.Combine(filePath, fileName);
filePaths.Add(filePath + ".pdf");
dstDoc.Save(filePath + ".pdf", SaveFormat.Pdf);
var options = new ImageSaveOptions(SaveFormat.Png) { PageCount = 1, Resolution = 120, UseAntiAliasing = true, PrettyFormat = true, UseHighQualityRendering = true };
for (var i = 0; i < dstDoc.PageCount; i++)
{
options.PageIndex = i;
dstDoc.Save(string.Format("{0}_{1}.png", filePath, i), options);
}

If it is a shared server, then most probably it is a security issue. Aspose.Words for .NET DLL needs access to the Windows registry, to find the fonts folder. Refer to http://www.aspose.com/docs/display/wordsnet/Considerations+When+Running+on+a+Shared+Server+Environment for more details.
A workaround is also possible to specify the path of folder, which has all the required fonts. Please see http://www.aspose.com/docs/display/wordsnet/How+to++Specify+True+Type+Fonts+Location for sample code.
I work with Aspose as Developer evangelist.

Related

Saxon CS: transform.doTransform cannot find out file from first transformation on windows machine but can on mac

I am creating an azure function application to validate xml files using a zip folder of schematron files.
I have run into a compatibility issue with how the URI's for the files are being created between mac and windows.
The files are downloaded from a zip on azure blob storage and then extracted to the functions local storage.
When the a colleague runs the transform method of the saxon cs api on a windows machine the method is able to run the first transformation and produce the stage 1.out file, however on the second transformation the transform method throws an exception stating that it cannot find the file even though it is present on the temp directory.
On mac the URI is /var/folders/6_/3x594vpn6z1fjclc0vx4v89m0000gn/T and on windows it is trying to find it at file:///C:/Users/44741/AppData/Local/Temp/ but the library is unable to find the file on the windows machine even if it is moved out of temp storage.
Unable to retrieve URI file:///C:/Users/44741/Desktop/files/stage1.out
The file is present at this location but for some reason the library cannot pick it up on the windows machine but it works fine on my mac. I am using Path.Combine to build the URI.
Has anyone else ran into this issue before?
The code being used for the transformations is below.
{
try
{
var transform = new Transform();
transform.doTransform(GetTransformArguments(arguments[Constants.InStage1File],
arguments[Constants.SourceDir] + "/" + schematronFile, arguments[Constants.Stage1Out]));
transform.doTransform(GetTransformArguments(arguments[Constants.InStage2File], arguments[Constants.Stage1Out],
arguments[Constants.Stage2Out]));
transform.doTransform(GetFinalTransformArguments(arguments[Constants.InStage3File], arguments[Constants.Stage2Out],
arguments[Constants.Stage3Out]));
Log.Information("Stage 3 out file written to : " + arguments[Constants.Stage3Out]);;
return true;
}
catch (FileNotFoundException ex)
{
Log.Warning("Cannot find files" + ex);
return false;
}
}
private static string[] GetTransformArguments(string xslFile, string inputFile, string outputFile)
{
return new[]
{
"-xsl:" + xslFile,
"-s:" + inputFile,
"-o:" + outputFile
};
}
private static string[] GetFinalTransformArguments(string xslFile, string inputFile, string outputFile)
{
return new[]
{
"-xsl:" + xslFile,
"-s:" + inputFile,
"-o:" + outputFile,
"allow-foreign=true",
"generate-fired-rule=true"
};
}```
So assuming the intermediary results are not needed as files but you just want the result (I assume that is the Schematron schema compiled to XSLT) you could try to run XSLT 3.0 using the API of SaxonCS (using Saxon.Api) by compiling and chaining your three stylesheets with e.g.
using Saxon.Api;
string isoSchematronDir = #"C:\SomePath\SomeDir\iso-schematron-xslt2";
string[] isoSchematronXslts = { "iso_dsdl_include.xsl", "iso_abstract_expand.xsl", "iso_svrl_for_xslt2.xsl" };
Processor processor = new(true);
var xsltCompiler = processor.NewXsltCompiler();
var baseUri = new Uri(Path.Combine(isoSchematronDir, isoSchematronXslts[2]));
xsltCompiler.BaseUri = baseUri;
var isoSchematronStages = isoSchematronXslts.Select(xslt => xsltCompiler.Compile(new Uri(baseUri, xslt)).Load30()).ToList();
isoSchematronStages[2].SetStylesheetParameters(new Dictionary<QName, XdmValue>() { { new QName("allow-foreign"), new XdmAtomicValue(true) } });
using (var schematronIs = File.OpenRead("price.sch"))
{
using (var compiledOs = File.OpenWrite("price.sch.xsl"))
{
isoSchematronStages[0].ApplyTemplates(
schematronIs,
isoSchematronStages[1].AsDocumentDestination(
isoSchematronStages[2].AsDocumentDestination(processor.NewSerializer(compiledOs)
)
);
}
}
If you only need the compiled Schematron to apply it further to validate an XML instance document against that Schematron you could even store the Schematron as an XdmDestination whose XdmNode you feed to XsltCompiler e.g.
using Saxon.Api;
string isoSchematronDir = #"C:\SomePath\SomeDir\iso-schematron-xslt2";
string[] isoSchematronXslts = { "iso_dsdl_include.xsl", "iso_abstract_expand.xsl", "iso_svrl_for_xslt2.xsl" };
Processor processor = new(true);
var xsltCompiler = processor.NewXsltCompiler();
var baseUri = new Uri(Path.Combine(isoSchematronDir, isoSchematronXslts[2]));
xsltCompiler.BaseUri = baseUri;
var isoSchematronStages = isoSchematronXslts.Select(xslt => xsltCompiler.Compile(new Uri(baseUri, xslt)).Load30()).ToList();
isoSchematronStages[2].SetStylesheetParameters(new Dictionary<QName, XdmValue>() { { new QName("allow-foreign"), new XdmAtomicValue(true) } });
var compiledSchematronXslt = new XdmDestination();
using (var schematronIs = File.OpenRead("price.sch"))
{
isoSchematronStages[0].ApplyTemplates(
schematronIs,
isoSchematronStages[1].AsDocumentDestination(
isoSchematronStages[2].AsDocumentDestination(compiledSchematronXslt)
)
);
}
var schematronValidator = xsltCompiler.Compile(compiledSchematronXslt.XdmNode).Load30();
using (var sampleIs = File.OpenRead("books.xml"))
{
schematronValidator.ApplyTemplates(sampleIs, processor.NewSerializer(Console.Out));
}
The last example writes the XSLT/Schematron validation SVRL output to the console but could of course also write it to a file.

Firebase Dynamic Links on Unity iOS says "Deep Link does not contain valid required params"

I'm using Firebase Dynamic Links for Unity, and I've got it working well with Android. I've even got a solution for Desktop, where the fallback link takes users to a webpage where I can provide instructions to the user for how to get their link content on Desktop.
On iOS, however, I always get errors like this when trying dynamic links:
[Firebase/Analytics][I-ACS023001] Deep Link does not contain valid required params. URL params: {
"_cpb" = 1;
"_cpt" = cpit;
"_fpb" = "CIAIEIAGGgVlbi11cw==";
"_iipp" = 1;
"_iumchkactval" = 1;
"_iumenbl" = 1;
"_osl" = "https://cgs.link/zu_tiles_hime?_iipp=1";
"_plt" = 260;
"_uit" = 1064;
apn = "com.finoldigital.cardgamesim";
cid = 8062347334713659136;
ibi = "com.finoldigital.CardGameSim";
isi = 1392877362;
link = "https://www.cardgamesimulator.com/link%%3Furl%%3Dhttps://www.cardgamesimulator.com/games/zu_tiles_hime/zu_tiles_hime.json";
sd = "Play Zu Tile: Hime on CGS!";
si = "https://www.cardgamesimulator.com/games/zu_tiles_hime/Banner.png";
st = "Card Game Simulator - Zu Tiles: Hime";
}
I saw in another issue that it could be because of ?, =, and & symbols in the link, so I url-encoded those, but I am still getting the same error.
For reference, my code for iOS is effectively:
private void Start()
{
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
{
var dependencyStatus = task.Result;
if (dependencyStatus != DependencyStatus.Available)
{
Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
return;
}
DynamicLinks.DynamicLinkReceived += OnDynamicLinkReceived;
});
}
I immediately log in OnDynamicLinkReceived, so this callback is clearly never happening. Does anybody know what I am doing wrong, or what I could do to get the dynamic link received callback?
For anyone who runs into the same issue:
I solved this by modifying my build script to add the values for FirebaseDynamicLinksCustomDomains and FirebaseAppDelegateProxyEnabled to Info.plist as part of my build process.
PostProcess code:
var pbxProjectPath = PBXProject.GetPBXProjectPath(buildPath);
var pbxProject = new PBXProject(); pbxProject.ReadFromFile(pbxProjectPath);
const string targetName = "Unity-iPhone"; var targetGuid = pbxProject.GetUnityMainTargetGuid();
var src = AssetDatabase.GetAssetPath(file);
var fileName = Path.GetFileName(src);
var dst = buildPath + "/" + targetName + "/" + fileName;
if (!File.Exists(dst)) FileUtil.CopyFileOrDirectory(src, dst); pbxProject.AddFile(targetName + "/" + fileName, fileName);
pbxProject.AddBuildProperty(targetGuid, "CODE_SIGN_ENTITLEMENTS", targetName + "/" + fileName);
pbxProject.WriteToFile(pbxProjectPath);
var plistPath = buildPath + "/Info.plist";
var plistDocument = new PlistDocument(); plistDocument.ReadFromString(File.ReadAllText(plistPath));
var rootDict = plistDocument.root;
rootDict.SetBoolean("FirebaseAppDelegateProxyEnabled", false);
PlistElementArray customDomains = rootDict.CreateArray("FirebaseDynamicLinksCustomDomains");
customDomains.AddString("https://cgs.link");
File.WriteAllText(plistPath);

HiQPdf Evaluation tag added when printing

I have a c# dll that uses HiQPdf to print a PDF from file. The issue is the printed PDF has a string added to the top left saying "HiQPdf Evaluation". The marigins are also greatly increased making the image smaller.
When I open the pdf and print from there it is fine. I couldn't find anything on the string being added so hoping someone here might have some insight :)
code:
public void PrintFromFile(string fileName, System.Drawing.Printing.PrinterSettings printerSettings)
{
var imagePrinter = new PdfPrinter();
imagePrinter.PrinterSettings.Copies = printerSettings.Copies;
imagePrinter.PrinterSettings.Duplex = printerSettings.Duplex;
imagePrinter.PrinterSettings.FromPage = printerSettings.FromPage;
imagePrinter.PrinterSettings.MaximumPage = printerSettings.MaximumPage;
imagePrinter.PrinterSettings.MinimumPage = printerSettings.MinimumPage;
imagePrinter.PrinterSettings.PrinterName = printerSettings.PrinterName;
imagePrinter.PrinterSettings.PrintFileName = printerSettings.PrintFileName;
imagePrinter.PrinterSettings.PrintRange = printerSettings.PrintRange;
imagePrinter.PrinterSettings.PrintToFile = printerSettings.PrintToFile;
imagePrinter.PrinterSettings.ToPage = printerSettings.ToPage;
imagePrinter.PrinterSettings.Collate = printerSettings.Collate;
var pdf = new MemoryStream(System.IO.File.ReadAllBytes("V:\\AccW2\\" + fileName));
pdf.Position = 0;
imagePrinter.PrintPdf(pdf);
}
If you have an HtmlToPdf element in you PrintPdf function you should set your SerialNumber
private void PrintPdf(string htmlbody, string pdfname)
{
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
// set a demo serial number
htmlToPdfConverter.SerialNumber = "-- HiQPdf Serial Number --";
}

Appcelerator App crashes when downloading large (>500mb) zip file

We are currently developing an iOS-App with Appcelerator which stores media files on the device for later viewing (pdf, mp4, zipped web pages).
We are now facing a problem with files above 500MB which crash the app on iPhone. The app is working on iPad2, but all iPhones tested crash (at random) when downloading these files.
The files are unzipped (all media files come with additional information inside the archive) via ti.compression.
The code used is (broken down to the relevant parts):
var zipDownloader = Ti.Network.createHTTPClient({
'onload' : function() {
var tempname = Math.floor((Math.random() * 10000000) + 1);
var dir = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, 'tempDownloads', tempname);
dir.createDirectory();
filename = '' + tempname + '.zip';
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'tempDownloads', filename);
f.write(this.responseData);
var Compression = require('ti.compression');
var zipFileName = Ti.Filesystem.applicationDataDirectory + 'tempDownloads/' + filename;
var outputDirectory = Ti.Filesystem.applicationDataDirectory + 'tempDownloads/' + tempname + '/';
var start = Math.floor(Date.now() / 1000);
var result = Compression.unzip(outputDirectory, zipFileName, true);
var finished = Math.floor(Date.now() / 1000) - start;
f.deleteFile();
Compression = null;
this.callback(outputDirectory);
}
});
zipDownloader.open('GET', url);
zipDownloader.callback = callback; // given in previous code, not relevant
zipDownloader.send();
Set the file property of the HTTPClient (https://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network.HTTPClient-property-file) instead of writing the file once it is downloaded.
This will work for larger files because it writes the data directly into the file. Otherwise it will try to cache your file first and your app might crash because of memory errors. Tried it with 500+MB files

How to copy attachments from a List into a document library via workflow activity

I currently have a task list, some of them contain file attachments. As part of a new workflow I'm creating in MOSS Designer I need to copy the attachments to files in a document library. What is the best way to do this? Is there an activity already made for this? Thanks!
I know it is an old question but for someone out there..
private void MoveAppraisalSupportDocs(SPListItemCollection sourceDocsList, SPList destinationDocsLib)
{
int sourceDocCnt = sourceDocsList.Count;
if (sourceDocCnt > 0)
{
for (int sd = 0; sd < sourceDocCnt; sd++)
{
SPListItem sourceItem = sourceDocsList[sd];
byte[] fileBytes = sourceItem.File.OpenBinary();
string destUrl = destinationDocsLib.RootFolder.Url + "/" + sourceItem.File.Name;
SPFile destFile = destinationDocsLib.RootFolder.Files.Add(destUrl, fileBytes, true /*true means overwrite */);
}
}
}

Resources