GOOGLE DOCS API Invalid requests[0].updateTextStyle: Index 4 must be less than the end index of the referenced segment, 2.", - api

I've created a document using Google Docs API, but when I try to modify its options or add text, it gives me this error:
http://prntscr.com/naf0nm
The thing is if I open the document and click enter many times ( to make many lines) then execution and modification works. Can anyone help me?? What do I need to do to not get this error?
String text1 = "hola, llegó papa";
List<Request> requests = new ArrayList<>();
requests.add(new Request().setInsertText(new InsertTextRequest()
.setText(text1)
.setLocation(new Location().setIndex(25))));
BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response = service.documents()
.batchUpdate(idDoc, body).execute();
Here the method to create doc:
private static void createDoc(Docs service) throws IOException {
Document doc = new Document()
.setTitle("TEXTO CAMBIADO");
doc = service.documents().create(doc)
.execute();
System.out.println("Created document with title: " + doc.getTitle());
idDoc = doc.getDocumentId();
}

It is very late for answer but it can help to others.
May be this answer can help you. someone has answered here
Also you have to write backword to get the last inserted text at the starting of doc.
I just found another way to write text at end of doc. You don't need to set the location, just do this way..
public void insertText(Docs docsService) throws IOException {
List<Request> requests = new ArrayList<>();
requests.add(new Request().setInsertText(new InsertTextRequest()
.setText("Name : {{NAME}}\n")
.setEndOfSegmentLocation(new EndOfSegmentLocation())));
requests.add(new Request().setInsertText(new InsertTextRequest()
.setText("\nDOB: {{DOB}}\n")
.setEndOfSegmentLocation(new EndOfSegmentLocation())));
requests.add(new Request().setInsertText(new InsertTextRequest()
.setText("\nMobile: {{MOBILE}}\n")
.setEndOfSegmentLocation(new EndOfSegmentLocation())));
BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response = docsService.documents()
.batchUpdate(Constants.DOCUMENT_ID, body).execute();
}

Related

How to addHeadher in Rest Assured when the list is already given but for few API's it changes

RequestSpecBuilder RS = new RequestSpecBuilder()
.setBaseUri(GetURL("StgURL"))
.addHeader("Content-Type", "application/json")
.addHeader("x-device-id", "kjbwejfbwkjefclw")
.addHeader("x-api-client", "abcjojnoenc")
.addHeader("x-platform", "Android")
.addHeader("x-country", "IN")
.addHeader("x-api-token", UserValidation_StepDefination.Token)
.addFilter(RequestLoggingFilter
.logRequestTo(Log))
.addFilter(ResponseLoggingFilter
.logResponseTo(Log))
.setContentType(ContentType.JSON);
In this case we have this set of header which is mandatory in all the API's but for other API's i have to add 1 or 2 Header More, not sure how i can achieve in Steps definition file
#Given("payload")
public void payload() throws IOException {
rqsp = given().spec(requestSpecifications());
}

Split a "tagged" PDF document into multiple documents, keeping the tagging

In a project I have to split a PDF document into two documents, one containing all blank pages, and one containing all pages with content.
For this job, I use a PdfReader to read the source file, and two pdfCopy objects (one for the blank pages document, one for the pages with content document) to write the files to.
I use GetImportedPage to read a PdfImportedPage, which is then added to one of the PdfCopy writers.
Now, the problem is the following: the source file is using the "tagged PDF format". To preserve this (which is absolutely required), I use the SetTagged() method on both PdfCopy writers, and use the extra third parameter in GetImportedPage(...) to keep the tagged format. However, when calling the AddPage(...) on the PdfCopy writer, I get an invalid cast exception:
"Unable to cast object of type 'iTextSharp.text.pdf.PdfDictionary' to type 'iTextSharp.text.pdf.PRIndirectReference'."
Anyone has any ideas on how to solve this ? Any hints ?
Also: the project currently refers version 5.1.0.0 of the itext libraries. In 5.4.4.0 the third parameter to GetImportedPage does not seem to be there anymore.
Below, you can find a code extract:
iTextSharp.text.Document targetPdf = new iTextSharp.text.Document();
iTextSharp.text.Document blankPdf = new iTextSharp.text.Document();
iTextSharp.text.pdf.PdfReader sourcePdfReader = new iTextSharp.text.pdf.PdfReader(inputFile);
iTextSharp.text.pdf.PdfCopy targetPdfWriter = new iTextSharp.text.pdf.PdfSmartCopy(targetPdf, new FileStream(outputFile, FileMode.Create));
iTextSharp.text.pdf.PdfCopy blankPdfWriter = new iTextSharp.text.pdf.PdfSmartCopy(blankPdf, new FileStream(blanksFile, FileMode.Append));
targetPdfWriter.SetTagged();
blankPdfWriter.SetTagged();
try
{
iTextSharp.text.pdf.PdfImportedPage page = null;
int n = sourcePdfReader.NumberOfPages;
targetPdf.Open();
blankPdf.Open();
blankPdf.Add(new iTextSharp.text.Phrase("This document contains the blank pages removed from " + inputFile));
blankPdf.NewPage();
for (int i = 1; i <= n; i++)
{
byte[] pageBytes = sourcePdfReader.GetPageContent(i);
string pageText = "";
iTextSharp.text.pdf.PRTokeniser token = new iTextSharp.text.pdf.PRTokeniser(new iTextSharp.text.pdf.RandomAccessFileOrArray(pageBytes));
while (token.NextToken())
{
if (token.TokenType == iTextSharp.text.pdf.PRTokeniser.TokType.STRING)
{
pageText += token.StringValue;
}
}
if (pageText.Length >= 15)
{
page = targetPdfWriter.GetImportedPage(sourcePdfReader, i, true);
targetPdfWriter.AddPage(page);
}
else
{
page = blankPdfWriter.GetImportedPage(sourcePdfReader, i, true);
blankPdfWriter.AddPage(page);
blankPageCount++;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception at LOC1: " + ex.Message);
}
The error occurs in the call to targetPdfWriter.AddPage(page); near the end of the code sample.
Thank you very much for your help.
Koen.

Adobe Echo Sign Sending PDF file

I am working on Adobe Echo sign,I have downloaded the sample code from their website, I am using this sample code for sendingdocument, it has some code missing in sendDocument method so I have changed it. It's giving SoapHeader Exception,with nothing in InnerException,
{"apiActionId=XHZI4WF4BV693YS"}
below is my code of sending document
public static void sendDocument(string apiKey, string fileName, string recipient)
{
ES = new EchoSignDocumentService16();
FileStream file = File.OpenRead(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,
"Test from SOAP: " + fileName,
"This is neat.",
fileInfos,
SignatureType.ESIGN,
SignatureFlow.SENDER_SIGNATURE_NOT_REQUIRED
);
DocumentKey[] documentKeys;
senderInfo = new SenderInfo(recipient, "password", "APIKEY");
documentKeys = ES.sendDocument(apiKey, senderInfo, documentInfo);
Console.WriteLine("Document key is: " + documentKeys[0].documentKey);
}
its giving exception on this line
documentKeys = ES.sendDocument(apiKey, senderInfo, documentInfo);
Can anyone suggest some sample code of Adobe Echo Sign?
On the account page of your login there is an API log you can check. If you check the log entry for your request you may find more information there.
I can't see anything immediately wrong with your code however the EchoSign API guide says that the 'tos' field is deprecated and that the recipients field should be used instead. Helpfully this means you can't use the paramaterised constructor. Try creating your document creation info as such (this is C# but if you need Java it should be straightforward to figure out):
RecipientInfo[] recipientInfo = new RecipientInfo[1];
recipientInfo[0] = new RecipientInfo
{
email = "recipient",
role = RecipientRole.SIGNER,
roleSpecified = true
};
DocumentCreationInfo documentCreationInfo = new DocumentCreationInfo
{
recipients = recipientInfo,
name = "Test from SOAP: " + fileName,
message = "This is neat.",
fileInfos = fileInfos,
signatureType = SignatureType.ESIGN,
signatureFlow = SignatureFlow.SENDER_SIGNATURE_NOT_REQUIRED
};
Note that when using the recipientInfo array it seems that the roleSpecified field must be set to true. This little field tripped me up for ages and I was receiving errors similar to yours.

Cached Variables in VSTO Office 2010

After having a look around the web, I have found the following posts (below) which are quite similar to my problem. However, after trying the solutions, I am still stuck.
VSTO Frustration
Setting cached variables in VSTO 3.0
Basically, I want to populate some data in a Excel file on a web server before I send it to the client.
Here is my code in the Workbook:
namespace Inno.Data.Excel
{
public partial class ThisWorkbook
{
[Cached]
public DataSet Config = new DataSet();
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
//InitializeCachedData();
var baseUrl = (string)Config.Tables["Config"].Rows[0].ItemArray[0];
var streamIds = (string)Config.Tables["Config"].Rows[0].ItemArray[1];
MessageBox.Show(baseUrl + " " + streamIds);
}
}
}
and on the server side I have the following:
let rootUrl = Uri(x.Request.Url.GetLeftPart(UriPartial.Authority))
let setUpData (report : Report) (sd : ServerDocument) =
let url = rootUrl.AbsoluteUri
let streamIds = String.Join(",", report.series |> Seq.map(fun s -> s.id))
let dt = new System.Data.DataTable("Config")
dt.Columns.Add("BaseUrl", typeof<String>) |> ignore
dt.Columns.Add("StreamIds", typeof<String>) |> ignore
dt.Rows.Add([|box url; box streamIds|]) |> ignore
dt.AcceptChanges()
let cache = sd.CachedData.HostItems.["Inno.Data.Excel.ThisWorkbook"]
let urlItem = cache.CachedData.["Config"]
urlItem.SerializeDataInstance(dt)
sd.Save()
sd.Close()
let initialiseDocument (report : Report) (path : string) =
let fileName = report.name.Replace(" ", "_") + ".xlsx"
let sd = (new ServerDocument(path))
sd |> setUpData report
fileName
let docPath = x.Request.MapPath(Path.Combine(liveReportPath, "Inno.Data.Excel.xlsx"))
let fileName = initialiseDocument report docPath
x.File(File.OpenRead(docPath), "application/vnd.ms-excel", fileName) :> ActionResult
However, when I go to open the file after it has downloaded, I get the following error:
Microsoft.VisualStudio.Tools.Applications.Runtime.CannotFindObjectToFillException: Cannot find any public instance member with ID Config in object Inno.Data.Excel.ThisWorkbook.
Things I have tried:-
Using a simple string rather than a DataSet
Calling StartCaching("Config")
Manipulating the ServerDocument in memory using the byte[] file overload
Copying the original Excel file and operating on the copy
But now I'm out of ideas. I see that a fair number of people have had this error, and as is pointed out in this post, there was a known bug in VSTO 3.0 with manipulating files in memory.
Thanks in advance.

How to read all pages from PDF?

I am using an sdk from pdftron,which reads a single page at a time. My code would be:
PDFDoc doc = new PDFDoc(input_path);
doc.InitSecurityHandler();
PageIterator itr = doc.GetPage(1);
for (line = txt.GetFirstLine(); line.IsValid(); line = line.GetNextLine()){
for (word = line.GetFirstWord(); word.IsValid(); word = word.GetNextWord()){
Console.WriteLine(word.GetString());
}
}
I want to read each and every page, I had posted my same problem in PDFTRON forums.But couldn't get the solution for this.
Is it possible to read each and every pages?
Yes,you can read each and every pages of pdf at a time.You need to do just s slight change initializing page iterator.
I have modified the code,and it works fine.
PDFDoc doc = new PDFDoc(input_path);
doc.InitSecurityHandler();
PageIterator itr = doc.GetPageIterator();
for (; itr.HasNext(); itr.Next()) // Read every page
{
for (line = txt.GetFirstLine(); line.IsValid(); line = line.GetNextLine())
{
for (word = line.GetFirstWord(); word.IsValid(); word = word.GetNextWord())
{
Console.WriteLine(word.GetString());
}
}
}
Hope this will help you.