How to Insert Hyperlinks into OO Writer Documents Using OpenOffice CLI Libraries - c#

On the page https://api.libreoffice.org/examples/examples.html#OLE_examples
there are 2 examples of working with the OpenOffice CLI libraries.
These examples show you how to insert a hyperlink into an OO Calc document. But it is not clear how to insert a hyperlink into an OO Writer document.
Here is the code I wrote:
static void Main(string[] args)
{
try
{
unoidl.com.sun.star.uno.XComponentContext localContext =
uno.util.Bootstrap.bootstrap();
unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)localContext.
getServiceManager();
XComponentLoader componentLoader = (XComponentLoader)
multiServiceFactory.createInstance("com.sun.star.frame.Desktop");
string fileName = "c:\\Users\\sbe.CSOFT-SPB\\Documents\\OO\\1.odt";
//string fileName = "c:\\Users\\sbe.CSOFT-SPB\\Documents\\OO\\t1.ods";
fileName = #"file:///" + fileName.Replace('\\', '/');
XComponent xComponent = componentLoader.loadComponentFromURL(
fileName, "_blank",
0, new unoidl.com.sun.star.beans.PropertyValue[0]);
if (fileName.ToLower().EndsWith(".odt")) // OO Writer document
{
unoidl.com.sun.star.text.XTextDocument xTextDocument =
(unoidl.com.sun.star.text.XTextDocument)xComponent;
unoidl.com.sun.star.text.XText xText = xTextDocument.getText();
unoidl.com.sun.star.text.XSimpleText xSimpleText =
(unoidl.com.sun.star.text.XSimpleText)xText;
unoidl.com.sun.star.text.XTextCursor xCursor = xSimpleText.createTextCursor();
unoidl.com.sun.star.lang.XMultiServiceFactory xServiceMan =
(unoidl.com.sun.star.lang.XMultiServiceFactory)xTextDocument;
// create a TextFrame (
Object objTextFrame = xServiceMan.createInstance("com.sun.star.text.TextFrame");
unoidl.com.sun.star.text.XTextFrame xTextFrame =
(unoidl.com.sun.star.text.XTextFrame)objTextFrame;
unoidl.com.sun.star.awt.Size aSize = new unoidl.com.sun.star.awt.Size(15000, 400);
((unoidl.com.sun.star.drawing.XShape)xTextFrame).setSize(aSize);
// insert the frame
xText.insertTextContent(xCursor, xTextFrame, false); // it's OK
// create a hyperlink
Object aHyperlinkObj = xServiceMan.createInstance("com.sun.star.text.TextField.URL");
xServiceMan.createInstance("com.sun.star.text.TextField.URL");
unoidl.com.sun.star.beans.XPropertySet xPropSet =
(unoidl.com.sun.star.beans.XPropertySet)aHyperlinkObj;
xPropSet.setPropertyValue(
"URL", new uno.Any("http://www.example.org"));
xPropSet.setPropertyValue(
"Representation", new uno.Any("hyperlink"));
// ... and insert
unoidl.com.sun.star.text.XTextContent xContent =
(unoidl.com.sun.star.text.XTextContent)aHyperlinkObj;
xText.insertTextContent(xCursor, xContent, false); // exception on this statemen
}
else // OO Calc document
{
unoidl.com.sun.star.sheet.XSpreadsheetDocument mxDocument =
(unoidl.com.sun.star.sheet.XSpreadsheetDocument)xComponent;
unoidl.com.sun.star.sheet.XSpreadsheets xSheets = mxDocument.getSheets();
unoidl.com.sun.star.container.XIndexAccess xSheetsIA =
(unoidl.com.sun.star.container.XIndexAccess)xSheets;
unoidl.com.sun.star.sheet.XSpreadsheet xSheet =
(unoidl.com.sun.star.sheet.XSpreadsheet)
xSheetsIA.getByIndex(0).Value;
// create a hyperlink
unoidl.com.sun.star.lang.XMultiServiceFactory xServiceMan =
(unoidl.com.sun.star.lang.XMultiServiceFactory)mxDocument;
Object aHyperlinkObj =
xServiceMan.createInstance("com.sun.star.text.TextField.URL");
unoidl.com.sun.star.beans.XPropertySet xPropSet =
(unoidl.com.sun.star.beans.XPropertySet)aHyperlinkObj;
xPropSet.setPropertyValue(
"URL", new uno.Any("http://www.example.org"));
xPropSet.setPropertyValue(
"Representation", new uno.Any("hyperlink"));
// ... and insert
unoidl.com.sun.star.text.XTextContent xContent =
(unoidl.com.sun.star.text.XTextContent)aHyperlinkObj;
unoidl.com.sun.star.table.XCell Ń…Cell = xSheet.getCellByPosition(0, 0);
unoidl.com.sun.star.text.XText xText =
(unoidl.com.sun.star.text.XText)xCell;
unoidl.com.sun.star.text.XTextCursor xTextCursor =
xText.createTextCursor();
xText.insertTextContent(xTextCursor, xContent, false); // it's OK
}
xComponent.dispose();
}
catch (System.Exception e)
{
string message = String.Format("Error.\n{0}\n{1}",
e.Message, e.StackTrace.TrimStart());
Debug.WriteLine(message);
}
}
Inserting a hyperlink into an OO Calc document in this code works, but on the insert statement of a hyperlink into an OO Writer document throws an exception.

In Writer, hyperlinks are not fields, but simply a property of characters.
Basic code:
xCursor.setString("hyperlink")
xCursor.goLeft(9, False)
xCursor.goRight(9, True)
xCursor.HyperLinkURL = "http://www.example.org"
C# CLI code:
xCursor.setString("hyperlink");
xCursor.goLeft(9, false);
xCursor.goRight(9, true);
unoidl.com.sun.star.beans.XPropertySet xPropSet =
(unoidl.com.sun.star.beans.XPropertySet)xCursor;
xPropSet.setPropertyValue("HyperLinkURL", new uno.Any("http://www.example.org"));

Related

How can change link type of pdf links by itext7?

I want edit to visible rectangle of links in file pdf:
If i use acrobat ,i can edit link type to "Visible Rectangle"
But with iText7 , How can change this value?
I try setting, but it not working:
string strPage = #"C:\test1.pdf";
string strPageNew = #"C:\result.pdf";
PdfReader reader = new PdfReader(strPage);
using (PdfWriter writer = new PdfWriter(strPageNew))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
PdfPage pdfPage = pdfDoc.GetPage(1);
var annotations = pdfPage.GetAnnotations();
if (annotations != null)
{
foreach (PdfAnnotation a in annotations)
{
if (a.GetSubtype().Equals(PdfName.Link))
{
PdfLinkAnnotation link = (PdfLinkAnnotation)a;
var action = link.GetAction();
if (action != null)
{
if (action.Get(PdfName.S).Equals(PdfName.URI))
{
PdfString destination = action.GetAsString(PdfName.URI);
link.SetFlag(4);
link.SetHighlightMode(PdfAnnotation.HIGHLIGHT_OUTLINE);
link.SetBorderStyle(PdfAnnotation.STYLE_SOLID);
link.SetColor(iText.Kernel.Colors.ColorConstants.RED );
}
}
}
}
}
}
}
reader.Close();

Paragraph not changing to desired format in ppt with openxml

I'm trying to edit a paragraph in pptx through changing its text, font size, font style and alignment.
This is what i have done so far:
**this is the method im using to call the update paragraph**
public static void Main(string[] args)
{
using (PresentationDocument presentationDocument = PresentationDocument.Open("ppturl", true))
{
// Get the presentation part of the presentation document.
PresentationPart presentationPart = presentationDocument.PresentationPart;
// Verify that the presentation part and presentation exist.
if (presentationPart != null && presentationPart.Presentation != null)
{
// Get the Presentation object from the presentation part.
Presentation presentation = presentationPart.Presentation;
// Verify that the slide ID list exists.
if (presentation.SlideIdList != null)
{
SlideId sourceSlide = presentation.SlideIdList.ChildElements[0] as SlideId;
SlidePart slidePart = presentationPart.GetPartById(sourceSlide.RelationshipId) as SlidePart;
updateParagraph(slidePart);
}
}
}
Console.ReadLine();
CreateHostBuilder(args).Build().Run();
}
**Here im extracting the title in the slide because this is what i need.**
public static void updateParagraph(SlidePart slidePart)
{
if (slidePart == null)
{
throw new ArgumentNullException("presentationDocument");
}
if (slidePart.Slide != null)
{
// Find all the title shapes.
var shapes = from shape in slidePart.Slide.Descendants<Shape>()
where IsTitleShape(shape)
select shape;
foreach (P.Shape shape in shapes)
{
D.Paragraph paragraph = shape.TextBody.Elements<D.Paragraph>().FirstOrDefault();
shape.TextBody.RemoveAllChildren<D.Paragraph>();
AddNewParagraph(shape, "This is a new Slide");
}
}
}
**This is where i am trying to add a new paragraph with specific style**
public static void AddNewParagraph(this P.Shape shape, string NewText)
{
D.Paragraph p = new D.Paragraph();
P.TextBody docBody = shape.TextBody;
Justification justification1 = new Justification() { Val = JustificationValues.Center };
p.ParagraphProperties=new D.ParagraphProperties(justification1);
D.Run run = new D.Run(new D.Text(NewText));
D.RunProperties runProp = new D.RunProperties() { Language = "en-US", FontSize = 9, Dirty = false };
run.AppendChild(runProp);
D.Text newText = new D.Text(NewText);
run.AppendChild(newText);
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine(runProp.FontSize.ToString());
Console.WriteLine("--------------------------------------------------------------");
p.Append(run);
docBody.Append(p);
}
This is giving me an error whenever im trying to open the pptx "repair pptx error".
Can someone please provide a clear solution specific to pptx and not doc.?
Thankful..
You can try using Aspose.Slides for .NET. The following code example shows you how to change some paragraph properties with this library:
using (var presentation = new Presentation("example.pptx"))
{
var firstShape = (IAutoShape) presentation.Slides[0].Shapes[0];
var firstParagraph = firstShape.TextFrame.Paragraphs[0];
var firstPortion = firstParagraph.Portions[0];
firstPortion.Text = "New text.";
firstPortion.PortionFormat.FontHeight = 24;
firstPortion.PortionFormat.FontBold = NullableBool.True;
firstParagraph.ParagraphFormat.Alignment = TextAlignment.Center;
presentation.Save("example.pptx", SaveFormat.Pptx);
}
You can also evaluate Aspose.Slides Cloud SDK for .NET. This REST-based API allows you to make 150 free API calls per month for API learning and presentation processing. The following code example shows you how to change the paragraph settings using Aspose.Slides Cloud:
var slidesApi = new SlidesApi("my_client_id", "my_client_key");
var fileName = "example.pptx";
var slideIndex = 1;
var shapeIndex = 1;
var paragraphIndex = 1;
var portionIndex = 1;
var firstPortion = slidesApi.GetPortion(
fileName, slideIndex, shapeIndex, paragraphIndex, portionIndex);
firstPortion.Text = "New text.";
firstPortion.FontHeight = 24;
firstPortion.FontBold = Portion.FontBoldEnum.True;
slidesApi.UpdatePortion(
fileName, slideIndex, shapeIndex, paragraphIndex, portionIndex, firstPortion);
var firstParagraph = slidesApi.GetParagraph(
fileName, slideIndex, shapeIndex, paragraphIndex);
firstParagraph.Alignment = Paragraph.AlignmentEnum.Center;
slidesApi.UpdateParagraph(
fileName, slideIndex, shapeIndex, paragraphIndex, firstParagraph);
I work as a Support Developer at Aspose.

Telerik Report in Asp.Net-Apply Filters in programatically

My Requirement: Apply fillers via c# coding(Not Design) ie, filterer salaries greater than 7000.
I have a class library and a web form in my project.
I am creating the report on class library and display report by using web form.
When I run my application it shows always the unfiltered data.
What i do to get Filtered data in Viewer.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Telerik.Reporting.Filter f1 = new Telerik.Reporting.Filter();
f1.Expression = "= Fields.Salary";
f1.Operator = Telerik.Reporting.FilterOperator.GreaterOrEqual;
f1.Value = "=7000";
EmpReport objEmpReport = new EmpReport(); objEmpReport.Filters.Add(f1);
TypeReportSource rptSource = new TypeReportSource(); rptSource.TypeName = typeof(EmpReport).AssemblyQualifiedName; this.ReportViewer1.ReportSource = rptSource;
}
}
working code:
// ...
using Telerik.Reporting;
using Telerik.Reporting.Processing;
// ...
void ExportToPDF(string reportToExport)
{
// all my reports are in trdx format - detect file type and use unpackage below for trdp files.
string currPath = HttpRuntime.AppDomainAppPath; // get the full path so deserialise works
reportToExport = currPath + #"Reports\" + reportToExport; // add folder and report name to path
UriReportSource uriReportSource = new UriReportSource { Uri = reportToExport }; // compressed to 1 line for brevity
Telerik.Reporting.Report myReport = DeserializeReport(uriReportSource); // extract report from xml format (trdx)
// Filters are client side (use params for server side) Here we work with the report object.
// set meaningful field name and values for your code, maybe even pass in as params to this function...
myReport.Filters.Add("UserId", FilterOperator.Equal , "1231");
var instanceReportSource = new Telerik.Reporting.InstanceReportSource(); // report source
instanceReportSource.ReportDocument = myReport; // Assigning Report object to the InstanceReportSource
// kinda optional, lots of examples just used null instead for deviceInfo
System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable(); // set any deviceInfo settings if necessary
ReportProcessor reportProcessor = new ReportProcessor(); // will do work
RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, deviceInfo); // GO!
if (!result.HasErrors)
{
this.Response.Clear();
this.Response.ContentType = result.MimeType;
this.Response.Cache.SetCacheability(HttpCacheability.Private);
this.Response.Expires = -1;
this.Response.Buffer = true;
this.Response.BinaryWrite(result.DocumentBytes);
this.Response.End();
}
else
{
Exception[] ex = result.Errors;
throw new Exception(ex[0].Message);
}
}
Telerik.Reporting.Report DeserializeReport(UriReportSource uriReportSource)
{
var settings = new System.Xml.XmlReaderSettings();
settings.IgnoreWhitespace = true;
using (var xmlReader = System.Xml.XmlReader.Create(uriReportSource.Uri, settings))
{
var xmlSerializer = new Telerik.Reporting.XmlSerialization.ReportXmlSerializer();
var report = (Telerik.Reporting.Report)xmlSerializer.Deserialize(xmlReader);
return report;
}
}
Telerik.Reporting.Report UnpackageReport(UriReportSource uriReportSource)
{
var reportPackager = new ReportPackager();
using (var sourceStream = System.IO.File.OpenRead(uriReportSource.Uri))
{
var report = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream);
return report;
}
}

Fill in Word template and save as pdf using openxml and openoffice

I am trying to fill a word document with data from an XML. I am using openXML to fill the document, which works great and save it as .docx. The thing is I have to open Word and save the document as an .odt and then use the OpenOffice SDK to open the .docx and save it as a pdf. When I don't save the .docx as .odt, the formatting is off.
What I need to be able to do is be able to either convert the .docx to .odt or save it originally as .odt.
Here is what I have right now:
static void Main()
{
string documentText;
XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
xmlDoc.Load("C:\\Cache\\MMcache.xml"); // Load the XML document from the specified file
XmlNodeList PatientFirst = xmlDoc.GetElementsByTagName("PatientFirst");
XmlNodeList PatientSignatureImg = xmlDoc.GetElementsByTagName("PatientSignatureImg");
byte[] byteArray = File.ReadAllBytes("C:\\Cache\\TransportationRunReporttemplate.docx");
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
{
using (StreamReader reader = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
documentText = reader.ReadToEnd();
}
using (StreamWriter writer = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
writer.Write(documentText);
}
}
// Save the file with the new name
File.WriteAllBytes("C:\\Cache\\MYFINISHEDTEMPLATE.docx", stream.ToArray());
}
}
private static void AddPicture(Bitmap bitmap)
{
using (WordprocessingDocument doc = WordprocessingDocument.Open("C:\\Cache\\MYFINISHEDTEMPLATE.docx", true))
{
//Bitmap image = new Bitmap("C:\\Cache\\scribus.jpg");
SdtElement controlBlock = doc.MainDocumentPart.Document.Body
.Descendants<SdtElement>()
.Where
(r =>
r.SdtProperties.GetFirstChild<Tag>().Val == "Signature"
).SingleOrDefault();
// Find the Blip element of the content control.
A.Blip blip = controlBlock.Descendants<A.Blip>().FirstOrDefault();
ImagePart imagePart = doc.MainDocumentPart
.AddImagePart(ImagePartType.Jpeg);
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
imagePart.FeedData(stream);
}
blip.Embed = doc.MainDocumentPart.GetIdOfPart(imagePart);
/* DW.Inline inline = controlBlock
.Descendants<DW.Inline>().FirstOrDefault();
// 9525 = pixels to points
inline.Extent.Cy = image.Size.Height * 9525;
inline.Extent.Cx = image.Size.Width * 9525;
PIC.Picture pic = inline
.Descendants<PIC.Picture>().FirstOrDefault();
pic.ShapeProperties.Transform2D.Extents.Cy
= image.Size.Height * 9525;
pic.ShapeProperties.Transform2D.Extents.Cx
= image.Size.Width * 9525;*/
}
ConvertToPDF(#"C:\Cache\MYFINISHEDTEMPLATE2.docx",#"C:\Cache\OpenPdf.pdf");
}
public static Bitmap Base64StringToBitmap(string base64String)
{
Bitmap bmpReturn = null;
byte[] byteBuffer = Convert.FromBase64String(base64String);
MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
memoryStream.Close();
memoryStream = null;
byteBuffer = null;
return bmpReturn;
}
public static void ConvertToPDF(string inputFile, string outputFile)
{
if (ConvertExtensionToFilterType(System.IO.Path.GetExtension(inputFile)) == null)
throw new InvalidProgramException("Unknown file type for OpenOffice. File = " + inputFile);
StartOpenOffice();
//Get a ComponentContext
var xLocalContext =
Bootstrap.bootstrap();
//Get MultiServiceFactory
var xRemoteFactory =
(XMultiServiceFactory)
xLocalContext.getServiceManager();
//Get a CompontLoader
var aLoader =
(XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");
//Load the sourcefile
XComponent xComponent = null;
try
{
xComponent = InitDocument(aLoader,
PathConverter(inputFile), "_blank");
//Wait for loading
while (xComponent == null)
{
Thread.Sleep(1000);
}
// save/export the document
SaveDocument(xComponent, inputFile, PathConverter(outputFile));
}
finally
{
if (xComponent != null) xComponent.dispose();
}
}
private static void StartOpenOffice()
{
var ps = Process.GetProcessesByName("soffice.exe");
if (ps.Length != 0)
throw new InvalidProgramException("OpenOffice not found. Is OpenOffice installed?");
if (ps.Length > 0)
return;
var p = new Process
{
StartInfo =
{
Arguments = "-headless -nofirststartwizard",
FileName = "soffice.exe",
CreateNoWindow = true
}
};
var result = p.Start();
if (result == false)
throw new InvalidProgramException("OpenOffice failed to start.");
}
private static XComponent InitDocument(XComponentLoader aLoader, string file, string target)
{
var openProps = new PropertyValue[1];
openProps[0] = new PropertyValue { Name = "Hidden", Value = new Any(true) };
XComponent xComponent = aLoader.loadComponentFromURL(
file, target, 0,
openProps);
return xComponent;
}
private static void SaveDocument(XComponent xComponent, string sourceFile, string destinationFile)
{
var propertyValues = new PropertyValue[2];
// Setting the flag for overwriting
propertyValues[1] = new PropertyValue { Name = "Overwrite", Value = new Any(true) };
//// Setting the filter name
propertyValues[0] = new PropertyValue
{
Name = "FilterName",
Value = new Any(ConvertExtensionToFilterType(System.IO.Path.GetExtension(sourceFile)))
};
((XStorable)xComponent).storeToURL(destinationFile, propertyValues);
}
private static string PathConverter(string file)
{
if (file == null || file.Length == 0)
throw new NullReferenceException("Null or empty path passed to OpenOffice");
return String.Format("file:///{0}", file.Replace(#"\", "/"));
}
public static string ConvertExtensionToFilterType(string extension)
{
switch (extension)
{
case ".odt":
case ".doc":
case ".docx":
case ".txt":
case ".rtf":
case ".html":
case ".htm":
case ".xml":
case ".wps":
case ".wpd":
return "writer_pdf_Export";
case ".xls":
case ".xlsb":
case ".ods":
return "calc_pdf_Export";
case ".ppt":
case ".pptx":
case ".odp":
return "impress_pdf_Export";
default: return null;
}
}
}
}
Just for information I cannot use anything that uses Interop because word will not be installed the machine. I am using OpenXML and OpenOffice
This is what I would try (details below):
1) try Doc format instead of DocX
2) switch to Libre Office and try DocX again
2) use the odf-converter to get a better DocX -> ODT conversion.
More details...
There's something called the odf-conveter (opensource) that can convert DocX->ODT which gives you (typically) more accurate DocX->ODT than Open Office. Take a look at odf-conveter-integrator by OONinja for pre-packaged versions.
Also, Libre Office has DocX support ahead of OpenOffice so you might get a better result simply by switching to Libre Office.
A further option is to start from Doc format rather than DocX. In the OpenOffice world that translates much better to ODT and then to PDF.
Hope that helps.
You may try to use Docxpresso to generate your .odt directly from HTML + CSS code and avoid any conversion issue.
Docxpresso is free for non-commercial use.

command line c# code works, but winforms code does not

I am working on a Adobe Echosign demo C# winforms application. My code is a direct copy of their command line code (with modifications), however, my code returns an error after it transmits the data.
This is the command line code from EchoSign that works
public static void sendDocument(string apiKey, string fileName, string formFieldLayerTemplateKey, string recipient)
{
FileStream file = getTestPdfFile(fileName);
secure.echosign.com.FileInfo[] fileInfos = new secure.echosign.com.FileInfo[1];
fileInfos[0] = new secure.echosign.com.FileInfo(fileName, null, file);
SenderInfo senderInfo = null;
string[] recipients = new string[1];
recipients[0] = recipient;
DocumentCreationInfo documentInfo = new DocumentCreationInfo(
recipients,
testPrefix + Path.GetFileName(file.Name),
testMessage,
fileInfos,
SignatureType.ESIGN,
SignatureFlow.SENDER_SIGNATURE_NOT_REQUIRED
);
if (formFieldLayerTemplateKey != null)
{
secure.echosign.com.FileInfo[] formFieldLayerTemplates = new secure.echosign.com.FileInfo[1];
formFieldLayerTemplates[0] = new secure.echosign.com.FileInfo(formFieldLayerTemplateKey);
documentInfo.formFieldLayerTemplates = formFieldLayerTemplates;
}
DocumentKey[] documentKeys;
documentKeys = ES.sendDocument(apiKey, senderInfo, documentInfo);
Console.WriteLine("Document key is: " + documentKeys[0].documentKey);
}
This is my code block that returns an error from their system:
public static void sendDocument(string apiKey, string fileName, string formFieldLayerTemplateKey, string recipient)
{
try
{
SenderInfo senderInfo = new SenderInfo();
senderInfo = null;
FileStream FileToSign = getTestPdfFile(fileName);
byte[] bytes = System.IO.File.ReadAllBytes("C:\\PROJECTS\\TestFile.pdf");
secure.echosign.com.FileInfo[] fileInfos = new secure.echosign.com.FileInfo[1];
fileInfos[0] = new EchoSignTest.secure.echosign.com.FileInfo();
fileInfos[0].fileName = fileName;
fileInfos[0].mimeType = null;
fileInfos[0].file = bytes;
RecipientInfo[] docRecipient = new RecipientInfo[1];
docRecipient[0] = new RecipientInfo();
docRecipient[0].email = recipient;
DocumentCreationInfo documentInfo = new DocumentCreationInfo();
documentInfo.recipients = docRecipient;
documentInfo.name = testPrefix + Path.GetFileName(FileToSign.Name);
documentInfo.message = testMessage;
documentInfo.fileInfos = fileInfos;
documentInfo.signatureType = SignatureType.ESIGN;
documentInfo.signatureFlow = SignatureFlow.SENDER_SIGNATURE_NOT_REQUIRED;
if (formFieldLayerTemplateKey != null)
{
secure.echosign.com.FileInfo[] formFieldLayerTemplates = new secure.echosign.com.FileInfo[1];
formFieldLayerTemplates[0] = new secure.echosign.com.FileInfo();
formFieldLayerTemplates[0].formKey = formFieldLayerTemplateKey;
documentInfo.formFieldLayerTemplates = formFieldLayerTemplates;
}
EchoSignDocumentService19PortTypeClient ES = new EchoSignDocumentService19PortTypeClient();
DocumentKey[] documentKeys = new DocumentKey[1];
documentKeys = ES.sendDocument(apiKey, senderInfo, documentInfo);
Console.WriteLine("Document key is: " + documentKeys[0].documentKey);
}
catch (NullReferenceException ex)
{
string errMessage = ex.Message;
}
catch (Exception ex)
{
string errMessage = ex.Message;
}
}
What is different between the two code blocks? The error may reside in the FileInfo[] or DocumentCreationInfo() blocks. I am perhaps not creating the objects as the system requires.
Any suggestions are appreciated.
The error seems to be the direct assignment of the bytes of the document you read to the fileInfos[0].file variable. In the documentation for FileInfo it states that the file parameter has to be the raw file content, encoded using base64, but you assign the raw file content without encoding it. When the constructor is called with a file stream like in your first example (the command-line one), the constructor seems to handle this automatically. You could try to change these lines in your Winforms example:
FileStream FileToSign = getTestPdfFile(fileName);
byte[] bytes = System.IO.File.ReadAllBytes("C:\\PROJECTS\\TestFile.pdf");
secure.echosign.com.FileInfo[] fileInfos = new secure.echosign.com.FileInfo[1];
fileInfos[0] = new EchoSignTest.secure.echosign.com.FileInfo();
fileInfos[0].fileName = fileName;
fileInfos[0].mimeType = null;
fileInfos[0].file = bytes;
into this code and try if this works:
FileStream FileToSign = getTestPdfFile(fileName);
secure.echosign.com.FileInfo[] fileInfos = new secure.echosign.com.FileInfo[1];
fileInfos[0] = new secure.echosign.com.FileInfo(fileName, null, FileToSign);
You should use the provided constructors instead of direct assignment to make sure all variables/parameters are handled properly.
The error you told about in your comments about the constructor that doesn't take 3 arguments could be a result of the EchoSignTest. prefix before your constructor call as it seems this is your own program's namespace and not the right namespace of the provided API.

Categories

Resources