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

בדף הזה של 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 מופיע במאמר בחירת היקפים של Google Drive API.

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

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

כדי להעתיק מסמך, משתמשים ב-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')

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