יצירה וניהול של מסמכים

בדף הזה ב-Google Docs API מוסבר איך לבצע משימות מסוימות ברמה גבוהה שכוללות מסמכי Google Docs, כמו:

  • יצירת מסמך
  • העתקת מסמך קיים

בפסקאות הבאות מתוארות המשימות האלה בפירוט.

יצירת מסמך ריק

כדי ליצור מסמך, משתמשים בשיטה documents.create באוסף documents.

דוגמת הקוד הבאה ממחישה איך ליצור מסמך ריק עם כותרת מסוימת:

Java

private static void createDoc(Docs service) throws IOException {
    Document doc = new Document()
            .setTitle("My Document");
    doc = service.documents().create(doc)
            .execute();
    System.out.println("Created document with title: " + doc.getTitle());
}

PHP

$title = 'My Document';
$document = new Google_Service_Docs_Document(array(
    'title' => $title
));

$document = $service->documents->create($document);
printf("Created document with title: %s\n", $document->title);

Python

title = 'My Document'
body = {
    'title': title
}
doc = service.documents() \
    .create(body=body).execute()
print('Created document with title: {0}'.format(
    doc.get('title')))

עבודה עם תיקיות ב-Google Drive

אין אפשרות ליצור מסמך ישירות בתוך תיקיית Drive ספציפית באמצעות Docs API. כברירת מחדל, המסמך שנוצר נשמר בתיקיית השורש של המשתמש ב-Drive.

עם זאת, יש שתי חלופות לשמירת קובץ בתיקייה ב-Drive:

בכל אחת מהאפשרויות האלה, צריך להוסיף את היקפי ההרשאות של Drive API כדי לאשר את הקריאה. מידע נוסף על היקפים ב-Drive זמין במאמר בחירת היקפים של ממשק API ב-Google Drive.

במאמר הטמעת תמיכה באחסון שיתופי מוסבר איך להעביר או ליצור קובץ בתיקייה של אחסון שיתופי.

העתקת מסמך קיים

כדי להעתיק מסמך, צריך להשתמש ב-method files.copy של Drive API.

דוגמת הקוד הבאה מראה איך מעתיקים מסמך קיים. אפשר למצוא את המזהה שבו צריך להשתמש לקריאה ל-Drive API בכתובת ה-URL של המסמך. למידע נוסף, ראו מזהה מסמך.

https://docs.google.com/document/d/DOCUMENT_ID/edit

Java

String copyTitle = "Copy Title";
File copyMetadata = new File().setName(copyTitle);
File documentCopyFile =
        driveService.files().copy(documentId, copyMetadata).execute();
String documentCopyId = documentCopyFile.getId();

Node.js

var copyTitle = "Copy Title";
let request = {
  name: copyTitle,
};
this.driveService.files.copy({
  fileId: documentId,
  resource: request,
}, (err, driveResponse) => {
  let documentCopyId = driveResponse.id;
});

PHP

<?php
$copyTitle = 'Copy Title';
$copy = new Google_Service_Drive_DriveFile(array(
    'name' => $copyTitle
));
$driveResponse = $driveService->files->copy($documentId, $copy);
$documentCopyId = $driveResponse->id;

Python

copy_title = 'Copy Title'
body = {
    'name': copy_title
}
drive_response = drive_service.files().copy(
    fileId=document_id, body=body).execute()
document_copy_id = drive_response.get('id')

שימו לב שצריך להשתמש בהיקף מתאים ב-API של Drive כדי לאשר את הקריאה. מידע נוסף על היקפים ב-Drive זמין במאמר בחירת היקפים של ממשק API ב-Google Drive.