How to export slides to HTML/PDF/DOC in google slides API - google-slides

I'm using google slides API to create powerpoint presentation.
Where additional required functionalities are-
Export to PDF
Export to HTML
Export to Doc/Image format.
Is there a way given by Slides API?

The Slides API doesn't support exports directly, but that functionality is available from the Drive API:
https://developers.google.com/drive/v3/reference/files/export
Just use the Slides presentationId as the Drive fileId.

#Sangram
Assuming that you already have created the slide deck, the process to convert Google Slides to PDF would be as follows:
import apiclient.http as client_methods
# exporting the slide deck and specifying the desired final file type
data = drive_client.files().export(fileId=slide_id, mimeType='application/pdf').execute()
# request body to be send together the upload method
body = {'name':file_name, 'mimeType':'application/pdf'}
# wrapping the binary (data) file with BytesIO class
fh = client_methods.BytesIO(data)
# creating the Media Io upload class for the file (note that our original slide data is of binary type)
media_body = client_methods.MediaIoBaseUpload(fh,
mimetype='application/pdf')
# drive API v3 - .create | drive API v2 - .insert
pdf_file_id = drive_client.files().create(body=body, media_body=media_body).execute()['id']
# extra step: moving to desirable folder destination with the function method
def move_files(drive_client, id_, folder_id):
file_ = drive_client.files().get(fileId=id_, fields='parents').execute()
drive_client.files().update(fileId=id_, addParents=folder_id,
removeParents=file_['parents'][0],
fields='id,parents').execute()
# calling the move_files function.
# drive_client is authorized client, folder_id = desired destination directory (from url).
move_files(drive_client, pdf_file_id, folder_id)
Hope this helps.
Resources:
Drive API v3 export method
Drive API v3 create method
Drive API v3 move files between folders

As #Codik mentioned, Google Slides API doesn't support exports directly but you can use Google Drive API for exporting.
Here is my solution. I am replacing some text in the sides as well before exporting.
$substitutions = [
'text_block_1' => "My First Text",
'text_block_2' => "My Second Text"
];
// You can fond the google slide Id in the URL
$templateId = "Here comes the Google Slide Id";
$client = $certificationService->getGoogleClient();
$driveService = new \Google_Service_Drive($client);
$slidesService = new \Google_Service_Slides($client);
$copy = new \Google_Service_Drive_DriveFile(array(
'name' => 'Pdf Name' . ' presentation'
));
$driveResponse = $driveService->files->copy($templateId, $copy);
$fileId = $driveResponse->id;
// replaceable text should be covered with {{}}
// example = {{text_block_1}}
$requests = [];
foreach ($substitutions as $key => $value) {
$requests[] = new \Google_Service_Slides_Request(
[
'replaceAllText' => [
'containsText' => [
'text' => '{{'.$key.'}}',
'matchCase' => true
],
'replaceText' => $value
]
]
);
}
$batchUpdateRequest = new \Google_Service_Slides_BatchUpdatePresentationRequest(array(
'requests' => $requests
));
$updateResponse = $slidesService->presentations->batchUpdate($fileId, $batchUpdateRequest);
// here you can specify the file type you want to export as
$response = $driveService->files->export($fileId, 'application/pdf', array('alt' => 'media'));
$content = $response->getBody()->getContents();
// delete the exported file from the Google Drive
$driveService->files->delete($fileId);
Note:- In order for this code to work, the google slides should be shared with the Google Service Account email.

Related

Populate Image & Image List Fields with Bolt CMS Programatically

I am attempting to create entries programaticaly in Bolt 4. I have managed to create basic text entries fine which covers the majority of fields I need to fill in however unsure how to go about image and image list types.
$content->setFieldValue('name', 'Test Name');
Works fine for most fields as stated but images field types looks like below in database and am unsure what the "Bolt / Symfony / Doctrine" way of generating below is:
{"media":11,"filename":"entity\/year\/month\/image.jpg","alt":"","0":""}
Which looks like some JSON formatted to contain a media ID, file path and an alt attribute. I'm guessing image lists are similar but with multiple of above but hoping there is a function I can use to generate this output as unsure how I would grab media ID etc.
Am assuming I may need to upload a file temporarily from an external URL and provide this to some function however cannot find any examples. Any help would be much appreciated.
Not quite sure on this but will answer anyway as it works and may help someone else, but would be good to clear some of the bits up.
Example of an Image:
//not sure what goes in media here but blank seemed to not work here but a 7 did as looked at example in database however worried this is wrong and should be an Id
$image = array('media' => '7', 'filename' => $filename, 'alt' => $image['Alt'], '0' => '');
$imageJSON = json_encode($image);
$content->setFieldValue('image', $image);
Example of an Image List:
$images = array();
foreach ($images as $image) {
$ImageId = $image['id'];
//images may be already on system but I had to download them here
if ($fileName = $this->downloadImage($propertyFile->{'url'}->__toString(), $ImageId)) {
//not sure what goes in media here but seemed to work blank for imagelist type and unsure what the 0 is on the end either
$image[] = array('media' => '', 'filename' => $filename, 'alt' => $image['Alt'], '0' => ''); }
}
$imageJSON = json_encode($image);
$content->setFieldValue('gallery', $image);

wordpress - woocommerce- woocommerce_api_authentication_error on api

I’m using the woocommerce api for my application, i’ve created the keys and apis and it did work fine , it authenticate and return the data via the api .
It’s been two days that it doesn’t connect any more , I’ve made a new api key but the same result.
I get this message when I run the url :
{"errors":[{"code":"woocommerce_api_authentication_error","message":"\u06a9\u0644\u06cc\u062f \u06cc\u06a9 \u0645\u0646\u0638\u0648\u0631\u0647 \u0646\u0627\u0645\u0639\u062a\u0628\u0631 \u0627\u0633\u062a. \u06a9\u0644\u06cc\u062f \u0642\u0628\u0644\u0627 \u0627\u0633\u062a\u0641\u0627\u062f\u0647 \u0634\u062f\u0647 \u0627\u0633\u062a."}]}
it says woocommerce_api_authentication_error , but I've created new keys and I'm sure the keys are correct .
can you help me . this is a sample code of mine :
$options = array(
‘debug’ => true,
‘return_as_array’ => false,
‘validate_url’ => false,
‘timeout’ => 30,
‘ssl_verify’ => false,
);
$client = new WC_API_Client(‘http://nodasht.com’,
“ck_4c25b06d7a9e507fbdeb06e338e20a2db1f7cc43”,
“cs_b89c9152510beb3cd915942cc4f33b91b720d62e”, $options);
$res = $client->products->get($row->ID);
$product = $res->product;
If you google bits of your message like this part \u06a9 you will be able to find out what the message is , thus know what the actual problem is.

WP REST API v2 Can't use filters

I Connecting with woocommerse with Oauth2.
But i can't use filters, example /wp-json/wp/v2/post&filter[category_name]=food
I get information about users, example http://my-site/wp-json/wp/v2/users, but on page i get info about first 10 users, i need more... When i use filter, example : http://my-site/wp-json/wp/v2/users?filter[posts_per_page]=5- filter not work
my code:
require('vendor/autoload.php');
const CLIENT_ID = 'my-ID';
const CLIENT_SECRET = 'my-secret';
const REDIRECT_URI = 'http://wooc/test.php';
const AUTHORIZATION_ENDPOINT = 'http://my-site/oauth/authorize';
const TOKEN_ENDPOINT = 'http://my-site/oauth/token';
$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET);
if (!isset($_GET['code']))
{
$auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
header('Location: ' . $auth_url);
die('Redirect');
}
else
{
$params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI);
$response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code',$params);
}
$client->setAccessToken("a6kpdxqqs3runou66ovzjjy54rvfubv64hhpdomn");
$data = $client->fetch("http://my-site/wp-json/wp/v2/users?filter[posts_per_page]=5");
echo "<pre>";
var_dump($data);
I do not understand where the error!
Please help. thank you
The API response filtering functionality has been superseded by more robust query parameters like ?categories=, ?slug= and ?per_page=.
In WordPress 4.7 the filter argument for any post endpoint was removed, The filter argument allows the posts to be filtered using WP_Query public query vars. This plugin restores the filter parameter for sites that were previously using it: https://github.com/luisfredgs/rest-filter
However, you can also convert your existing code to remove filter.
Something along the lines of this:
http://my-site/wp-json/wp/v2/users?filter[posts_per_page]=5
becomes this:
http://my-site/wp-json/wp/v2/users?posts_per_page=5

Drupal - Importing a taxonomy with migrate module from a table and creating/updating existing terms

I need to import a list of terms into my taxonomy from a source I loaded in the database.
The problem is I allready have this taxonomy on my site (loaded wihtout migrate) with terms that are used by reference in other content, so I got to keep existing term and update them or create the new ones.
To link my taxonomy source and the existing taxonomy I have an unique code for each term, so I added a code field to my vocabulary and filled it for each existing term.
I am currently able to create and update terms with my current Migration class, but if the name of my term on the site and the name of the term in my source is different, the import will create a new term instead of updating its name even if the code is the same.
Here my Migration Class :
class TotoMigration extends Migration {
private $list_term = array();
public function __construct($arguments) {
parent::__construct();
$this->softDependencies = array('TotoParent');
// get data from the custom table containing the new terms to create or update
$query = db_select('toto', 'f')
->fields('f', array(
'CODE', // code
'LIBLONG', // name
'PARENT', // parent
)
);
$this->source = new MigrateSourceSQL($query);
$this->destination = new MigrateDestinationTerm('toto_tax');
$this->map = new MigrateSQLMap($this->machineName,
array(
'CODE' => array('type' => 'varchar',
'length' => 5,
'not null' => TRUE,
'description' => 'Code',
)
),
MigrateDestinationTerm::getKeySchema()
);
$this->addFieldMapping('name', 'LIBLONG');
$this->addFieldMapping('field_code', 'CODE');
$this->addFieldMapping('parent', 'PARENT')
->arguments(array('source_type' => 'tid'))
->sourceMigration('TotoParent');
// create a list of existing toto terms with code => tid
$list_term = db_query("select fc.field_code_value, ttd.tid
from taxonomy_term_data ttd
left join taxonomy_term_hierarchy tth on tth.tid=ttd.tid
left join field_data_field_code fc on fc.entity_id = ttd.tid
where ttd.vid=10
and tth.parent!=0;")->fetchAllKeyed();
}
public function prepareRow($row) {
// Always include this fragment at the beginning of every prepareRow()
// implementation, so parent classes can ignore rows.
if (parent::prepareRow($row) === FALSE) {
return FALSE;
}
// if the destination is not mapped in migrate we tell him where to go
if (!isset($row->migrate_map_destid1) && isset($list_term[$row->CODE])) {
$row->migrate_map_destid1 = $list_term[$row->CODE];
}
}
}
I then load the import with drush (and --update option).
I must be missing something, if anyone got a clue it will be welcome.
After many tries, the problem reside in the fact the module Migrate does not support Creating content and Updating content in the same migration class (I even read it will sometime claim to update content and just do nothing).
So the solution is pretty simple, create 2 classes :
One for Creating content
One for Updating content
Your Creating class will be the same.
Your Updating class will need to have a systemeOfRecord set to DESTINATION :
$this->systemOfRecord = Migration::DESTINATION;
So it knows to only update and not recreate the content, it will keep current fields not mapped and update fields mapped that are not part of the MigrateSQLMap :
$this->map = new MigrateSQLMap($this->machineName,array(...));
The tricky part will be to find corresponding nid/tid of your content so you can map it to your imported data and then to separate data used to update or create content.

How do I post a photo to a Facebook event?

I've been using the PHP SDK to try and post photos to a test user's event on Facebook:
$c = 0;
$facebook->setFileUploadSupport(true);
while ($c < count($_FILES['file']['name'])) {
aFile = $_FILES['file'];
//..other code for ui and validity checks..//
$real = realpath($aFile["tmp_name"][$c]);
$attachment = array('message' => 'Test upload');
$attachment['image'] = '#'.$real; //also tried other keys. Please see below...
try {
$result = $facebook->api('/'.$event_id.'/photos?access_token='.$access_token, 'post', $attachment);
}
catch (FacebookApiException $e) {
echo('Could not post image to Facebook:'.var_export($e));
}
$c++;
}
Unfortunately, all I get is errors:
'message' => 'An unexpected error has occurred. Please retry your request later.', 'type' => 'OAuthException', 'code' => 2
I've been trying for two days and this is the only upload code I have so I'm hardly overloading Facebook with (in my case) attempting to send a 500x500 jpg file every so often.
If I alter the ../photos?access_token=… to ../feed?access_token=.. then the text gets posted but not the image.
I've also tried handling the image with:
$attachment[basename($real)] = '#'.$real;
and
$attachment['source'] = '#'.$real;
and
$attachment['picture'] = '#'.$real;
All with no success for local files. But the last key option on $attachment will allow a post with a URL to a picture on a (random) website.
Could someone tell me whether I'm 'post'ing to the correct open graph edge or if there's a mistake in my code for handling the image's data?
I think the problem was a mixture of test user accounts being corrupted or old and of my file path's.
I deleted the test user and completely recreated new ones and that along with a dummy file placed in a place I knew I could get to worked with the facebook command:
$photo_return = $facebook->api($event_id.'/photos', 'POST', array('source' => '#dummy_file.jpg', 'message' => 'Photo post'));

Resources