Hey everyone, I’m trying to figure out how to make a new Google Doc with some text already in it using the API. I can get the content from one doc, but I’m having trouble putting it into a new one.
Here’s what I’ve got so far:
// Getting content from an existing doc
DocumentService docService = new DocumentService();
ExistingDoc oldDoc = docService.fetchDocument(OLD_DOC_ID);
DocContent content = oldDoc.extractContent();
// Trying to make a new doc with the content
NewDoc newDoc = new NewDoc();
newDoc.setDocName("Still Not Working");
newDoc.fillWithContent(content);
CreatedDoc result = docService.createDocument(newDoc);
But it’s not working like I hoped. The new doc is empty. Am I missing something obvious? Has anyone done this before?
I checked the API docs but I’m still confused. Any help would be awesome!
I encountered a similar issue in one of my projects. I discovered that the Google Docs API separates document creation from content insertion, so you need to complete those steps individually. First, create the document and obtain its ID; then use the batchUpdate method to insert your content. It can be tricky to make sure formatting is preserved because copying over from another document might require handling paragraph and text styles specifically. If you’re working with a large volume of text, breaking it into smaller chunks for separate updates can help prevent timeout issues.
I’ve encountered a similar issue before. The key is to use the ‘batchUpdate’ method after creating the new document. Here’s a modified version of your code that should work:
DocumentService docService = new DocumentService();
ExistingDoc oldDoc = docService.fetchDocument(OLD_DOC_ID);
String content = oldDoc.extractContent();
NewDoc newDoc = new NewDoc();
newDoc.setDocName("Pre-filled Document");
CreatedDoc result = docService.createDocument(newDoc);
List<Request> requests = new ArrayList<>();
requests.add(new Request().setInsertText(new InsertTextRequest()
.setText(content)
.setLocation(new Location().setIndex(1))));
docService.documents().batchUpdate(result.getDocumentId(), new BatchUpdateDocumentRequest().setRequests(requests)).execute();
This approach creates the document first, then uses ‘batchUpdate’ to insert the content. Make sure you have the necessary permissions to modify the new document.