In pdf hyperlink modify date of pdf at runtime using C# .net - c#

One pdf is generated and I am adding link of website in some text of pdf using aspose and below code,
var link = new Aspose.Pdf.Annotations.LinkAnnotation(document.Pages[t.p], userSignRect)
{
Action = new Aspose.Pdf.Annotations.GoToURIAction(requestHostAddress.Replace("http://", "https://") + "/document-details/" + documentId)
};
Now I want to append pdf's modified date run time in hyperlink.
Example : https://document-details/documentId/ ModifiedDateofPdfRuntime
Please help me/guide me how to do that.
Edit: I do not want current modified date.
Usecase : We have generated pdf and given to user with our basic hyperlink url in pdf.(which is a happy scenario)
But if someone is altering my pdf then i won't know and pdf's url will still route to my website.
To overcome same i want to append PDF's modified date object in url which will fetch pdf info and get date.
something like this, is it possible ?

This should work.
Action = new Aspose.Pdf.Annotations.GoToURIAction(requestHostAddress
.Replace("http://", "https://") + "/document-details/" + documentId + "_" + DateTime.Now.ToString())

I guess you are looking for something like this
DateTime creation = File.GetCreationTime(#"C:\test.txt");
DateTime modification = File.GetLastWriteTime(#"C:\test.txt");
and then you can add checks to check if file is modified or not.
code is copied from here.

You need to use ModDate property from PdfFileInfo class:
using Aspose.Pdf.Facades;
//...
var fileInfo = new PdfFileInfo(dataDir + "GetFileInfo.pdf");
var modificationDate = fileInfo.ModDate;
Hope it helps. Otherwise, feel free to ask me.
Note: I am working as Developer Evangelist at Aspose.

Related

CefSharp possible to load html content?

I need to create a application which loads a html "template" file and parse them with current data values. So far no problemm but does anyone knows how to load the parsed html value into the cefsharp browser ?
I found some old topics here with an "loadHtml()" function. But this function isnt there anymore.
Thanks in advance
You need to add a using CefSharp; statement to your code to access the LoadHtml extensions methods.
chromiumWebBrowser.LoadHtml(html);
const string html = "<html><head><title>Test</title></head><body><h1>Html Encoded in URL!</h1></body></html>";
var base64EncodedHtml = Convert.ToBase64String(Encoding.UTF8.GetBytes(html));
browser.Load("data:text/html;base64," + base64EncodedHtml);
From the project wiki on github: Loading HTML/CSS/JavaScript/etc from disk/database/embedded resource/stream

Rotativa breaks the HTML when there is more than one page

I am creating a pdf from HTML using Rotativa, and my code looks like this
var CustomSwitches = "--footer-right \"Date: [date] [time]\" " + "--footer-center \"Page: [page] of [toPage]\" --footer-line --footer-font-size \"9\" --footer-spacing 5 --footer-font-name \"calibri light\"";
var rotativaOptions = new DriverOptions { CustomSwitches = CustomSwitches,PageSize = Size.A4};
return new ViewAsPdf("~/Views/Partials/Report/SummaryReportspdf.cshtml")
{
RotativaOptions = rotativaOptions
};
All looks good to me, but when there is more than one page, page breaks even. And it looks like below image
How can I solve this issue?
I solved this problem using the latest version of wkhtmltopdf (currently version 0.12.5)
You can download it from here: https://wkhtmltopdf.org/downloads.html
Hope it helps!
Syncfusion HTML to PDF converter in C# provides an option to convert HTML to PDF without text and image split across the pages. Refer the help documentation for more information
https://help.syncfusion.com/file-formats/pdf/convert-html-to-pdf/webkit#split-text
Note: I work for Syncfusion.

C# DocX : add internal link

In the DocX library available at : https://github.com/WordDocX/DocX
It is possible to add some hyperlink but i haven't found a way to add internal link.
Does anyone know how to add a link to specific paragraph or to a bookmark ?
The way I've found is:
synthesisDocument.AddHyperlink("Link",new Uri("file:///path/to/doc/file.doc#MY_BOOKMARK"));
synthesisDocument.Paragraphs[0].InsertHyperl‌​ink(h)
That way resolve your problem, but only in doc format, when you export to PDF it doesn't work.
I hope it helps
As mentioned #BookMark does work if the Uri is created with the UriKind.Relative flag:
var uri = new Uri("#" + BookMark,UriKind.Relative);
var hyperLink = doc.AddHyperlink(textToDisplay, uri );
Now to use the hyperlink on a paragraph, p:
p.InsertHyperlink(hyperLink,indexToInsertAt);
I achieved exactly the result I wanted using this in both .docx and .pdf
Hope it works for you,
Nick

Receiving message of issue with content in Excel File

I am currently building an Excel file by hand using OpenXml. I'm in the process of adding the sheets, however, I have come across an issue. I have a loop that adds the names of each sheet in but once it runs and I try to open the file, I get the following message:
"We found a problem with some content in 'FileName.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, Click Yes."
I think the issue might be due that I am adding in the name of each sheet using a string variable. When I take it out and add something else, it works. Below is my code where I am looping through and adding my sheets.
//Technology Areas
foreach (DataRow dr in techAreaDS.Rows)
{
var data = dr["TechAreaName"].ToString().Split('-');
var techArea = data[2].TrimStart();
var techAreaSheet = new Sheet { Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = sheetId, Name = techArea };
sheets.Append(techAreaSheet);
sheetId++;
}
I've seen people mention it is an issue with cells having strings that can be converted into strings, but in this case, the string will always be a string. Any help would be appreciated.
EDIT: I've figured out the problem. The issue is the Name property has a Max Length of 31. One of my items has a 42 length, hence the error. I did find a cool set of code to validate my OpenXml. Link.
UPDATE:
Oddly enough, someone thinks this question was about finding some code to help validate what I was doing. It was not... The question is clear: why was I receiving an error when trying to name sheets. I was not asking for validation code, though I found some.
I do ask that if you wish to help, please read the question versus assume what I was asking, and if you don't know what I wish to have answered, ask...
In order to find out the issue(s) causing this error, you need to validate the generated document.
Besides using the built in validation method as described here, which doesn't show you all issues as I found out, I suggest that you download and install Microsoft's Open XML SDK 2.5 for Microsoft Office.
It contains Microsoft's Open XML SDK 2.5 Productivity Tool, which is very helpful here:
Create a copy of the damaged XLSX file, and apply the fixes as Microsoft Excel is suggesting (suppose you have the files FileName_corrupt.xlsx and FileName_fixed.xlsx
Then, run Microsoft's Open XML SDK 2.5 Productivity Tool, open FileName_corrupt.xlsx, select "Compare Files" and specify the 2nd file FileName_fixed.xlsx. This allows you to compare the XML structure of both files.
Let Microsoft's Open XML SDK 2.5 Productivity Tool generate C# code from both files: Open them first, then right-click on the root level and select "Reflect Code". This will create C# code which allows you to generate the same file. Save both C# code versions (i.e. FileName_corrupt.cs and FileName_fixed.cs)
Now you can compare the differences via Visual Studio: Either use
devenv.exe /diff FileName_corrupt.cs FileName_fixed.cs
to compare them, or use the batch file I've created to launch the VS compare - this is a hidden feature in Visual Studio, it allows to compare 2 local files being not part of TFS.
This way you should be able to work out the differences and allow you to fix your code.
NOTE: For a first validation, I do suggest to use the validation code. Only if it still fails, use the steps above. For validation you can use
public static string ValidateOpenXmlDocument(OpenXmlPackage pXmlDoc, bool throwExceptionOnValidationFail=false)
{
using (var docToValidate = pXmlDoc)
{
var validator = new DocumentFormat.OpenXml.Validation.OpenXmlValidator();
var validationErrors = validator.Validate(docToValidate).ToList();
var errors = new System.Text.StringBuilder();
if (validationErrors.Any())
{
var errorMessage = string.Format("ValidateOpenXmlDocument: {0} validation error(s) with document", validationErrors.Count);
errors.AppendLine(errorMessage);
errors.AppendLine();
}
foreach (var error in validationErrors)
{
errors.AppendLine("Description: " + error.Description);
errors.AppendLine("ErrorType: " + error.ErrorType);
errors.AppendLine("Node: " + error.Node);
errors.AppendLine("Path: " + error.Path.XPath);
errors.AppendLine("Part: " + error.Part.Uri);
if (error.RelatedNode != null)
{
errors.AppendLine("Related Node: " + error.RelatedNode);
errors.AppendLine("Related Node Inner Text: " + error.RelatedNode.InnerText);
}
errors.AppendLine();
errors.AppendLine("==============================");
errors.AppendLine();
}
if (validationErrors.Any() && throwExceptionOnValidationFail)
{
throw new Exception(errors.ToString());
}
if (errors.Length > 0)
{
System.Diagnostics.Debug.WriteLine(errors.ToString());
}
return errors.ToString();
}
along with
public static void ValidateExcelDocument(string fileName)
{
using (var xlsx = SpreadsheetDocument.Open(fileName, true))
{
ValidateOpenXmlDocument(xlsx);
}
}
With a slight modification, you can easily use the code above for Microsoft Word validation too:
public static void ValidateWordDocument(string fileName)
{
using (var docx = WordprocessingDocument.Open(fileName, true))
{
ValidateOpenXmlDocument(docx);
}
}
I've figured out the problem. The issue is the Name property has a Max Length of 31 characters. The text I'm trying to use sometimes exceeds that limit (one has 42 characters). I also found a pretty cool set of code to validate my Open Xml to find out what the specific issue is. Link

how can I rename a document with a unique ID in OpenXML

I'm creating a copy of an Office 2010 word document for some OpenXML automation. The below code blows up on File.Copy saying it doesn't like the path\name combination of the copiedPath variable
string mainPath = #"Path\Name.docx";
string copiedPath = #"Path\Name" +
DateTime.Now.ToString().Replace("/", "-").Replace(" ", "-") +".docx";
File.Copy(mainPath, copiedPath);
If I make the following change the code works fine:
string copiedPath = #"Path\Name_Test_.docx";
but since this is going to be used on the company intranet I'd like a better way to separate the different requests by users. Has anyone pulled off what I'm trying to do or can you see what I'm doing wrong?
You are not allowed to have a : in a file name, so you will have to replace that charactor as well.

Categories