copy attachment from other document on fly - xpages

After I save my current XPages, in the event postNewDocument of datasources..I would to copy on the fly in the backend Domino Document without saving of disk the attachment from another document andI have found this solution:
var attachments:java.util.Vector = session.evaluate("#AttachmentNames", docReply);
for (var i = 0; i < attachments.size(); i++) {
embeddedObj = docReply.getAttachment(attachments.get(i).toString());
if (embeddedObj != null) {
bufferInStream = new java.io.BufferedInputStream(embeddedObj.getInputStream());
}
}
How how can I add every attachment stream into a RichTextItem of my current Domino Document?
Tnx
update 29 january 14: Tnx to #Sven I have insert this code into my PostSavedocument event..
But now I have another problem...seem that damage the MIME my "Body" that is the rt mime.
If I open with my Notes Client the document with this RT mime I see only the new attachments and not the original HTML content of CKEDITOR (If I comment the follow code...work correct)....Now I have the problem to re-edit exist MIME filed
session.setConvertMime(false);
var doc:NotesDocument=document1.getDocument(true);
var mimeRoot:NotesMIMEEntity=doc.getMIMEEntity("Body");
var docAttach:NotesDocument=database.getDocumentByUNID('XXXXXXXUNID'); //doc where are the attachmetns files MIME or RICHTEXT
var XSPReply=wrapDocument(docAttach); //function in Xsnippets from Opentntf.org
var listattachs=XSPReply.getAttachmentList("Body");
for (var i=0; i<listattachs.length; i++) {
var is=null;
var att = listattachs[i];
var persistentName = att.getPersistentName()==null?att.getName():att.getPersistentName();
var cid = att.getCID();
var eo:NotesEmbeddedObject = docAttach.getAttachment(persistentName);
if (null != eo) {
var child:NotesMIMEEntity=mimeRoot.createChildEntity(); //create child of original mail
var emailHeader:NotesMIMEHeader = child.createHeader("Content-Disposition");
emailHeader.setHeaderVal("attachment; filename=\"" + persistentName+ "\"");
emailHeader = child.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
var is = new java.io.BufferedInputStream(eo.getInputStream());
var stream:NotesStream = session.createStream();
stream.setContents(is);
child.setContentFromBytes(stream, att.getType(),NotesMIMEEntity.ENC_IDENTITY_BINARY);
}
}
doc.closeMIMEEntities(true,"Body")
doc.save()
session.setConvertMime(true);

You can try to add the attachments as MIME Entities. Have a look here for an example: Link

Related

SPO & CSOM & Can't upload a document to a document library, but I can create a folder

I'm getting a list view threshold issue when attempting to upload a document to a document library. Let me give you the back story.
My site is on SPO and I'm using CSOM to create a folder and then add a uploaded document to that folder.
The service account I'm using to authentication to SPO is a site collection admin.
My CSOM code can create the folder, but cannot upload a document to that folder because SharePoint says that we've hit the list view threshold.
The document library that we're trying to upload a document to has over 20K items in it.
The default view that we're using only has one column selected, we have the Title and Created field indexed and the document library uses the modern experience.
We've been using the same code for a while, but as of October 2019 things stopped working.
Any ideas ? Provided below is the code that I'm using
using (ClientContext ctx = new ClientContext(SPUrl))
{
ctx.Credentials = new SharePointOnlineCredentials(spuser, securePassword);
Web webSite = ctx.Web;
ctx.Load(webSite);
ctx.ExecuteQuery();
List list = ctx.Web.Lists.GetByTitle("TempDoc");
ctx.Load(list);
var lst = ctx.Web.Lists.GetByTitle("TempDoc");
var fld1 = lst.RootFolder.Folders.Add(FolderName);
fld1.Update();
ctx.ExecuteQuery();
foldersatus = true;
try
{
int FileLen;
FileLen = Request.Files[upload].ContentLength;
byte[] input = new byte[FileLen];
System.IO.Stream fileStream;
// Initialize the stream.
fileStream = Request.Files[upload].InputStream;
// Read the file into the byte array.
fileStream.Read(input, 0, FileLen);
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = input;
newFile.Url = filename;
List docs = webSite.Lists.GetByTitle("TempDoc");
ctx.Load(docs.RootFolder);
ctx.Load(docs.RootFolder.Folders);
Microsoft.SharePoint.Client.File uploadFile1 = docs.RootFolder.Folders[0].Files.Add(newFile);
ctx.ExecuteQuery();
}
I found out the problem. The issue was the call ctx.Load(docs.RootFolder.Folders); I had removed this piece of code, I was now able to upload documents.
My sample test code(the lib has more than 10k files).
List docs = context.Web.Lists.GetByTitle("largeLib1");
var filePath = #"C:\Lee\template.xlsx";
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
FileCreationInformation flciNewFile = new FileCreationInformation();
flciNewFile.ContentStream = fs;
flciNewFile.Url = System.IO.Path.GetFileName(filePath);
flciNewFile.Overwrite = true;
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile);
context.Load(uploadFile);
context.ExecuteQuery();
}
Or(the folder has more than 10k files)
Folder folder = context.Web.GetFolderByServerRelativeUrl("/sites/xxx/largeLib1/set2");
var filePath = #"C:\Lee\template.xlsx";
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
FileCreationInformation flciNewFile = new FileCreationInformation();
flciNewFile.ContentStream = fs;
flciNewFile.Url = System.IO.Path.GetFileName(filePath);
flciNewFile.Overwrite = true;
Microsoft.SharePoint.Client.File uploadFile = folder.Files.Add(flciNewFile);
context.Load(uploadFile);
context.ExecuteQuery();
}

Add text/content to PDF files (Angular)

I work on project and try to implement signature pad on pdf file.
I make a signature with angular2-signaturepad package and view the pdf file with ng2-pdf-viewer.
now i'm looking for a way
to add the signature to Existing pdf file.
What is the best way?
Try this if it helps using Html2canvas in anglar. you could send your html content to pdf and view it.
Example function
htmlToPdf() {
var data = document.getElementById('html2pdf'); // You can pass the id here for your signature
html2canvas(data).then(canvas => {
var imgWidth = 208;
var pageHeight = 100;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
var position = 0;
pdf.addImage(contentDataURL, 'PNG', 3, position, imgWidth, imgHeight);
pdf.fromHTML()
pdf.save(this.data+'.pdf'); // Generated PDF
});
}

Docusign - Error opening PDF downloaded through the Rest API

With the REST api, I am trying to get the documents out of a completed envelope. My header is using X-DocuSign-Authentication.
EnvelopesApi ap = new EnvelopesApi();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
EnvelopeDocumentsResult edr = ap.ListDocuments((AccountId, "xxx-xx-xxx");
List<EnvelopeDocument> docs = edr.EnvelopeDocuments;
foreach(EnvelopeDocument doc in docs)
{
Stream stream1 = ap.GetDocument(AccountId, "xxx-xx-xxx", doc.DocumentId);
StreamReader reader = new System.IO.StreamReader(stream1, encode);
var data = reader.ReadToEnd();
StreamWriter writer = new StreamWriter(#"C:\mysigneddoc.pdf");
writer.Write(data);
writer.Close();
}
When I try to open the completed pdf, I get the error stating that
the signers identity has not been verified.
Any ideas where I might be going wrong?
Please look at the API recipe here to download the documents from an envelope.
var ap = new EnvelopesApi();
var edr = ap.ListDocuments((AccountId, "xxx-xx-xxx");
List<EnvelopeDocument> docs = edr.EnvelopeDocuments;
foreach(EnvelopeDocument doc in docs)
{
// GetDocument() API call returns a MemoryStream
var docStream = (MemoryStream)envelopesApi.GetDocument(accountId, envelopeId, doc.DocumentId);
// let's save the document to local file system
filePath = #"C:\temp\" + Path.GetRandomFileName() + ".pdf";
fs = new FileStream(filePath, FileMode.Create);
docStream.Seek(0, SeekOrigin.Begin);
docStream.CopyTo(fs);
fs.Close();
}
You can also download the combined documents in an envelope using the GetEnvelopeDocuments api. You are not required to query for each individual document.
Combined PDF
Pass the string combined as the documentId.
Retrieve a PDF that contains the combined content of all documents and the certificate.
string envelopeId = "XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
string accountId = "XXXXXX";
var envApi = new EnvelopesApi();
// GetDocument() API call returns a MemoryStream
var docStream = (MemoryStream)envApi.GetDocument(accountId, envelopeId, "combined");
// let's save the document to local file system
string filePath = #"C:\temp\" + Path.GetRandomFileName() + ".pdf";
var fs = new FileStream(filePath, FileMode.Create);
docStream.Seek(0, SeekOrigin.Begin);
docStream.CopyTo(fs);
fs.Close();
ZIP file
Pass the string archive as documentId
Retrieve a ZIP archive that contains all of the PDF documents, the certificate, and any .WAV files used for voice authentication.
var envApi = new EnvelopesApi();
// GetDocument() API call returns a MemoryStream
var docStream = (FileStream)envApi.GetDocument(accountId, envelopeId, "archive");
// let's save the document to local file system
string filePath = #"C:\temp\" + Path.GetRandomFileName() + ".zip";
var fs = new FileStream(filePath, FileMode.Create);
docStream.Seek(0, SeekOrigin.Begin);
docStream.CopyTo(fs);
fs.Close();

Any way to upload a file to sharepoint through webservice

I have a requirement to upload files to sharepoint using sharepoint webservices.
Are there any sharepoint services which consumes the file content as base64 data inside soap request?
This resource will help you to understand this.
Here's the relevant content from the article in case the link is broken for future readers:
Let’s Upload a Document
To upload a document we need to add another service reference to
http://server/sites/personal/_vti_bin/copy.asmx. This is the Copy
service.
Here is the code to upload a document to the document library:
CopySoapClient client = new CopySoapClient();
if (client.ClientCredentials != null)
{
client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
}
try
{
client.Open();
string url = "http://server/sites/personal/My Documents Library/Folder One/Folder Two/";
string fileName = "test.txt";
string[] destinationUrl = { url + fileName };
byte[] content = new byte[] { 1, 2, 3, 4 };
// Description Information Field
FieldInformation descInfo = new FieldInformation
{
DisplayName = "Description",
Type = FieldType.Text,
Value = "Test file for upload"
};
FieldInformation[] fileInfoArray = { descInfo };
CopyResult[] arrayOfResults;
uint result = client.CopyIntoItems(fileName, destinationUrl, fileInfoArray, content, out arrayOfResults);
Trace.WriteLine("Upload Result: " + result);
// Check for Errors
foreach (CopyResult copyResult in arrayOfResults)
{
string msg = "====================================" +
"SharePoint Error:" +
"\nUrl: " + copyResult.DestinationUrl +
"\nError Code: " + copyResult.ErrorCode +
"\nMessage: " + copyResult.ErrorMessage +
"====================================";
Trace.WriteLine(msg);
_logFactory.ErrorMsg(msg);
}
}
finally
{
if (client.State == CommunicationState.Faulted)
{
client.Abort();
}
if (client.State != CommunicationState.Closed)
{
client.Close();
}
}
You can use Spservises to achieve the desired functionality. Please see the code below:
function UploadFile(listName,itemId,files){
var filereader = {},
file = {};
var fileLength = files.length;
//loop over each file selected
for(var i = 0; i < files.length; i++)
{
file = files[i];
filereader = new FileReader();
filereader.filename = file.name;
filereader.onload = function() {
var data = this.result,
n=data.indexOf(";base64,") + 8;
//removing the first part of the dataurl give us the base64 bytes we need to feed to sharepoint
data= data.substring(n);
$().SPServices({
operation: "AddAttachment",
listName: listName,
asynch: true,
listItemID:itemId,
fileName: this.filename,
attachment: data,
completefunc: testFunction(i,fileLength)
});
};
filereader.onabort = function() {
alert("The upload was aborted.");
};
filereader.onerror = function() {
alert("An error occured while reading the file.");
};
//fire the onload function giving it the dataurl
filereader.readAsDataURL(file);
}
Here files is the files returned by using a html file control to upload.
I was looking for a simple soap request which can do the job, and with the help of comments from #ElvisLikeBear I was able to make use of the CopyIntoItems web service in http://server/sites/personal/_vti_bin/copy.asmx.
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Body>
<CopyIntoItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<SourceUrl>fileName.ext</SourceUrl>
<DestinationUrls>
<string>{your share point location to where the file has to be uploaded.}http://mySharepoint/mysharepointsite/fileName.ext</string>
</DestinationUrls>
<Fields>
<!--FieldInformation Type="Note" DisplayName="CustomerMeta_0" InternalName="" Id="12345678-4564-9875-1236-326598745623" Value="xxx" /-->
</Fields>
<Stream>Base 64 encoded content </Stream>
</CopyIntoItems>
</SOAP:Body>
</SOAP:Envelope>

streaming iText pdf directly to lotus email using xpages

i'm trying to stream a newly generated pdf (using itext) directly to the body of lotus notes email as an attachment. but i'm getting following error while setting body of the email from bytes
"com.ibm.jscript.types.GeneratedWrapperObject$StaticField incompatible with com.ibm.jscript.types.FBSValue"
following is my completed code(placed in a button of an xpage). Any help would be greatly appreciated
session.setConvertMIME(false);
outputStream:java.io.ByteArrayOutputStream = new java.io.ByteArrayOutputStream();
writePdf(outputStream);
var bytes = outputStream.toByteArray();
var inputStream:java.io.ByteArrayInputStream = new java.io.ByteArrayInputStream(bytes);
var db:NotesDatabase= session.getDatabase("","mail.box")
if (!db.isOpen()) {
print ("No mailbox!")
}
else
{
var doc:NotesDocument=db.createDocument()
doc.replaceItemValue("Form","Memo")
doc.replaceItemValue("From",context.getUser().getCommonName())
doc.replaceItemValue("Principal",context.getUser().getCommonName())
doc.replaceItemValue("SendTo","a#b.com");
doc.replaceItemValue("Recipients","a#b.com");
doc.replaceItemValue("CopyTo","a#b.com");
doc.replaceItemValue("INetFrom","b#c.com");
var strFileName="temp.pdf"
var body:NotesMIMEEntity = doc.createMIMEEntity('Body');
var hdr:NotesMIMEHeader = body.createHeader("Subject");
hdr.setHeaderValAndParams("Subject")
hdr=body.createHeader("MIME-Version")
hdr.setHeaderValAndParams("1.0")
body.setPreamble("multipart message in MIME")
var child1:NotesMIMEEntity= body.createChildEntity()
hdr = child1.createHeader("Content-Disposition")
hdr.setHeaderValAndParams('attachment; filename="test.pdf"')
var stream:NotesStream = session.createStream();
stream.setContents(inputStream)
child1.setContentFromBytes(stream, "application/pdf", body.ENC_IDENTITY_BINARY)
child1.encodeContent(body.ENC_BASE64)
doc.closeMIMEEntities(true,"Body")
doc.save(true, true);
// Restore conversion
session.setConvertMIME(true);
}
function writePdf(outputStream) {
var document:com.itextpdf.text.Document = new com.itextpdf.text.Document();
var writer = com.itextpdf.text.pdf.PdfWriter.getInstance(document,outputStream);
document.open();
document.addTitle("Test PDF");
document.addSubject("Testing email PDF");
document.addKeywords("iText, email");
document.addAuthor("Author");
document.addCreator("Creator");
var passChunk:com.itextpdf.text.Chunk = new com.itextpdf.text.Chunk("Hello");
document.add(new com.itextpdf.text.Paragraph(passChunk));
document.close();
}
you probably would be better off writing a small Java wrapper class.
For starters you need:
var stream:NotesStream = session.createStream();
stream.setContents(inputStream);
stream.setPosition(0);
so the stream is at the beginning.
Update:
Also you have:
var bytes = outputStream.toByteArray();
var inputStream:java.io.ByteArrayInputStream = new java.io.ByteArrayInputStream(bytes);
stream.setContents(inputStream);
where I would write:
var bytes = outputStream.toByteArray();
stream.write(bytes);
Still, make a helper in Java.
Note: iText is GPL licenced. Unless the application you build is internal use only, you either need to buy a commercial license or GPL your code as well. Look at Apache PDFBox for an alternative

Resources