How to set the encode in PhpSpreadsheet\Reader\Xlsx? - encode

I want to use PhpSpreadsheet convert xlsx to pdf, it's succeed.
But the Chinese word in xlsx is error.
And the setInputEncoding method is not found.
What can I do? please give me guide
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load($public['root'].'/' . $fileName);
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Mpdf');
$pdfName = str_replace($extension, 'pdf', $fileName);
$writer->save($public['root'].'/' . $pdfName);

You can set Font Family in file xlsx.
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load($public['root'].'/' . $fileName);
$styleArray = array(
'font' => array(
'name' => 'Verdana' // change your font
));
$spreadsheet->getDefaultStyle()->applyFromArray($styleArray);

The question is fixed.
First I download the yahei.ttf and put it to mpdf/ttfonts.
Then regist it in mpdf/src/Config/FontVariables.php.
Finally find the line 41 at PhpSpreadsheet/Writer/Pdf/Mypdf.php and change the code like this
$pdf = $this->createExternalWriterInstance(array_merge($config, ['default_font' => 'yahei']));
$pdf->setDisplayMode('fullpage');
$pdf -> useAdobeCJK = TRUE;
$pdf ->autoScriptToLang = true;
$pdf -> autoLangToFont = true;

Related

Upload Offline Conversion migration to V9

I used to upload offline conversion using following code in v201809 version as provided at
https://github.com/googleads/googleads-php-lib/blob/master/examples/AdWords/v201809/Remarketing/UploadOfflineConversions.php
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
$session = (new AdWordsSessionBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->withClientCustomerId($customerid)->enablePartialFailure()->build();
$adWordsServices = new AdWordsServices();
$offlineConversionService = $adWordsServices->get($session, OfflineConversionFeedService::class);
$conversionName="OfflineConv";
$feed = new OfflineConversionFeed();
$feed->setConversionName($conversionName);
$feed->setConversionTime($conversionTime);
$feed->setConversionValue($conversionValue);
$feed->setGoogleClickId($gclid);
$offlineConversionOperation = new OfflineConversionFeedOperation();
$offlineConversionOperation->setOperator(Operator::ADD);
$offlineConversionOperation->setOperand($feed);
$offlineConversionOperations = [$offlineConversionOperation];
$result = $offlineConversionService->mutate($offlineConversionOperations);
Now I am upgrading to V9, I have used the code as provided at
https://github.com/googleads/google-ads-php/blob/main/examples/Remarketing/UploadOfflineConversion.php
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
$googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->build();
//$conversionName="OfflineConv";
$conversionName = ConversionActionType::WEBPAGE;
$clickConversion = new ClickConversion([
'conversion_action' => ResourceNames::forConversionAction($customerId, $conversionName),
'gclid' => $gclid,
'conversion_value' => $conversionValue,
'conversion_date_time' => $conversionTime,
'currency_code' => 'USD'
]);
$conversionUploadServiceClient = $googleAdsClient->getConversionUploadServiceClient();
$result = $conversionUploadServiceClient->uploadClickConversions($customerid, [$clickConversion], true);
The problem is when we set $conversionName="OfflineConv"; we get following error.
Resource name 'customers/9025381111/conversionActions/OfflineConv' is malformed: expected 'customers/{customer_id}/conversionActions/{ConversionType.conversion_type_id}'., at conversions[0].conversion_action
and when we set $conversionName = ConversionActionType::WEBPAGE; we get following error.
This customer does not have an import conversion action that matches the conversion action provided., at conversions[0].conversion_action
Can someone help me?
Conversion Name must match the conversion action that you've already set up in your account. You're passing the enum value for the type.
It should be something like $conversionName = "OfflineConversions"
where "OfflineConversions" is exactly the name of the conversion in the conversions section of the web UI.
ConversionName has been removed from V9, use $conversionActionId as in example on github.
You need to try use parameter ctId from url your "OfflineConversions" in Google Ads UI as $conversionActionId.
Or try the solution from here.
For your example, replace this
$conversionName = ConversionActionType::WEBPAGE;
on this
$conversionName = {ctId from url};
You need to first create a click conversion
click_conversion = adwords_client.get_type("ClickConversion")
conversion_action_service = adwords_client.get_service('ConversionActionService')
click_conversion.conversion_action = (
conversion_action_service.conversion_action_path(
customer_id, conversion_action_id
)
)
The conversion_action_id is equivalent to conversion_name of previous version.
You can find the id using following snippet
ads: GoogleAdsServiceClient = self.adwords_client.get_service('GoogleAdsService')
pages = ads.search(query="SELECT conversion_action.id, conversion_action.name FROM conversion_action where conversion_action.name={conversion_name}", customer_id={customer_id})
for page in pages:
print(page.conversion_action)
Then you upload the conversion
click_conversion.gclid = gclid
click_conversion.conversion_value = conversion_value
click_conversion.conversion_date_time = conversion_time
click_conversion.currency_code = currency_code
conversion_upload_service = self.adwords_client.get_service("ConversionUploadService")
request = self.adwords_client.get_type("UploadClickConversionsRequest")
request.customer_id = customer_id
request.conversions.append(click_conversion)
request.partial_failure = True
conversion_upload_response = (
conversion_upload_service.upload_click_conversions(
request=request,
)
)
uploaded_click_conversion = conversion_upload_response.results[0]
print(
f"Uploaded conversion that occurred at "
f'"{uploaded_click_conversion.conversion_date_time}" from '
f'Google Click ID "{uploaded_click_conversion.gclid}" '
f'to "{uploaded_click_conversion.conversion_action}"'
)

PhpSpreadsheet - How to make part of the text bold

How do I bold several words I want in a cell?
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\{Font, Border, Alignment};
use PhpOffice\PhpSpreadsheet\RichText\RichText;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
....
$richText = new \PhpOffice\PhpSpreadsheet\RichText\RichText();
$richText->createText('This invoice is ');
$payable = $richText->createTextRun('payable within thirty days after the end of the month');
$payable->getFont()->setBold(true);
$payable->getFont()->setItalic(true);
$payable->getFont()->setColor( new \PhpOffice\PhpSpreadsheet\Style\Color( \PhpOffice\PhpSpreadsheet\Style\Color::COLOR_DARKGREEN ) );
$richText->createText(', unless specified otherwise on the invoice.');
$spreadsheet->getActiveSheet()->getCell('A18')->setValue($richText);
from: https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#add-rich-text-to-a-cell

PhpSpreadsheet Notice: Undefined offset: 4

I have been struggling with finding a way to read excel files in a directory, copy the worksheet called "Division" into a new file, then number the new worksheets increment by one - Division1, Division2, etc...
The following is my code, which I am receiving a warning for undefined index, which is not a big deal, but it only creates a new excel file with only four worksheets, when there should be over 240 worksheets.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
$exportedFiles = scandir('PhpSpreadsheet/Export');
$inputFileNames = [];
$sheetnames = [];
$outfile = 'all-together-now.xlsx';
foreach($exportedFiles as $key=> $value) {
if ($value == '.' || $value == '..') {
} else {
array_push($inputFileNames, 'PhpSpreadsheet/Export/' . $value);
array_push($sheetnames, 'Division');
}
}
$inputFileType = 'Xlsx';
$reader = IOFactory::createReader($inputFileType);
$reader->setLoadSheetsOnly($sheetnames);
$contador = 1;
foreach ($inputFileNames as $book => $inputFileName) {
echo ('$inputFileName: ' . $inputFileName) . '</br>';
$reader = IOFactory::createReader("Xlsx");
$spreadsheet = $reader->load($inputFileName);
$clonedWorksheet = clone $spreadsheet->getSheetByName('Division');
$clonedWorksheet->setTitle('Division' . $contador);
$spreadsheetMain = $reader->load($outfile);
$spreadsheetMain->addSheet($clonedWorksheet);
$writer = IOFactory::createWriter($spreadsheetMain, "Xlsx");
$writer->save($outfile);
$contador++;
}
The following are the warning notices:
Notice: Undefined offset: 4 in
PhpOffice\PhpSpreadsheet\Writer\Xlsx->save( )
PhpOffice\PhpSpreadsheet\Spreadsheet->garbageCollect( )
As usual, thanks in advance
Part of the solution was bumping up the memory and the other was to use addSheet()
The following is the code that works:
ini_set('memory_limit','32768M');
use PhpOffice\PhpSpreadsheet\IOFactory;
require_once 'PhpSpreadsheet/src/Bootstrap.php';
$exportedFiles = scandir('PhpSpreadsheet/Export');
$inputFileNames = [];
$sheetnames = [];
$outfile = 'all-together-now.xlsx';
foreach($exportedFiles as $key=> $value) {
if ($value == '.' || $value == '..') {
} else {
array_push($inputFileNames, 'PhpSpreadsheet/Export/' . $value);
array_push($sheetnames, 'Division');
}
}
$inputFileType = 'Xlsx';
$reader = IOFactory::createReader($inputFileType);
$reader->setLoadSheetsOnly($sheetnames);
$contador = 1;
foreach ($inputFileNames as $book => $inputFileName) {
echo ('$inputFileName: ' . $inputFileName) . '</br>';
$reader = IOFactory::createReader("Xlsx");
$spreadsheet = $reader->load($inputFileName);
$spreadsheet->getSheetByName('Division')->getStyle('Division');
$clonedWorksheet = clone $spreadsheet->getSheetByName('Division');
$clonedWorksheet->setTitle('Division' . $contador);
/* open new file for writing spread sheets to it */
$spreadsheetMain = $reader->load($outfile);
$spreadsheetMain->addSheet($clonedWorksheet);
$writer = IOFactory::createWriter($spreadsheetMain, "Xlsx");
$writer->save($outfile);
$contador++;
}
$spreadsheet->disconnectWorksheets();
echo "The process has completed";
die();
The aforementioned script created an excel workbook with 247 worksheets from the 247 excel files

How can I generate report using Google adwords api without downloading the file?

How can I generate the report CAMPAIGN_PERFORMANCE_REPORT without downloading the file (for example just showing the result).
Here is actually what I do:
$reportQuery = 'SELECT CampaignId,CampaignName, Impressions, Clicks, Ctr , Cost '
. ' FROM CAMPAIGN_PERFORMANCE_REPORT '
. ' WHERE CampaignId = '.$campaignId.' DURING '.$date.','.$date;
// Download report.
ReportUtils::DownloadReportWithAwql($reportQuery, $filePath, $user,$reportFormat, $options);
$dataArray =file($filePath);
I download the file, then I read from the data to show it up.
Actualy i didn't found a way except that i generate that file then i read from it and i use that result :
$reportQuery = 'SELECT CampaignId,CampaignName, Impressions, Clicks, Ctr , ConversionRate '
. ' FROM CAMPAIGN_PERFORMANCE_REPORT '
. ' WHERE CampaignId = '.$id.' DURING '.$date.','.$date;
// Download report.
ReportUtils::DownloadReportWithAwql($reportQuery, $filePath, $user,$reportFormat, $options);
$dataArray =file($filePath);
foreach ($dataArray as $value) {
$data = explode(",", $value);
$resultat[$i-1]['jours'] = $date;
$resultat[$i-1]['impressions'] = $data[2];
$resultat[$i-1]['clicks'] = $data[3];
$resultat[$i-1]['taux_click'] = $data[4];
$resultat[$i-1]['taux_conversion'] = $data[5];
}
echo json_encode($resultat);
Hope it helps.
After a day I found the solution:
In the source of the lib the method DownloadReport of Utils/ReportUtils.php say that:
Downloads a new instance of an existing report definition. If the path parameter is specified it will be downloaded to the file at that path, otherwise it will be downloaded to memory and be returned as a string.
You can set NULL to path and use the return value
$filePath = null;
$stringOfResult = $reportUtils->DownloadReport($reportDefinition, $filePath, $user, $options);
//now you can parse the result

cannot preserve space between runs

i want to generate a word document
as an input i have this string "open packaging conventions" and each word will have a different style
the result should be open packaging conventions
WordprocessingDocument document = WordprocessingDocument.Create(
#"C:\test PFE.docx",
WordprocessingDocumentType.Document
);
MainDocumentPart mainDocumentPart = document.AddMainDocumentPart();
mainDocumentPart.Document = new Document();
mainDocumentPart.Document.AddNamespaceDeclaration("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006");
mainDocumentPart.Document.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
mainDocumentPart.Document.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
mainDocumentPart.Document.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
mainDocumentPart.Document.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
mainDocumentPart.Document.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
mainDocumentPart.Document.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
mainDocumentPart.Document.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
mainDocumentPart.Document.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
Body documentBody = new Body();
mainDocumentPart.Document.Append(documentBody);
StyleDefinitionsPart styleDefinitionsPart =
mainDocumentPart.AddNewPart<StyleDefinitionsPart>();
FileStream stylesTemplate =
new FileStream("styles.xml", FileMode.Open, FileAccess.Read);
styleDefinitionsPart.FeedData(stylesTemplate);
styleDefinitionsPart.Styles.Save();
#region Titre du document
Paragraph titleParagraphe = new Paragraph() { RsidParagraphAddition = "00AF4948", RsidParagraphProperties = "00625634", RsidRunAdditionDefault = "00625634" }; ;
Run run = new Run();
RunProperties rpr = new RunProperties();
RunStyle rstylr = new RunStyle { Val = "style1" };
run.Append(rpr);
Text t = new Text("open");
run.Append(t);
titleParagraphe.Append(run);
run = new Run();
rpr = new RunProperties();
rstylr = new RunStyle { Val = "style2" };
run.Append(rpr);
t = new Text("packaging")
{
Space = new DocumentFormat.OpenXml.EnumValue<DocumentFormat.OpenXml.SpaceProcessingModeValues> { InnerText = "preserve" }
};
run.Append(t);
titleParagraphe.Append(run);
run = new Run();
rpr = new RunProperties();
rstylr = new RunStyle { Val = "style1" };
run.Append(rpr);
t = new Text("conventions")
{
Space = new DocumentFormat.OpenXml.EnumValue<DocumentFormat.OpenXml.SpaceProcessingModeValues> { InnerText = "preserve" }
};
run.Append(t);
titleParagraphe.Append(run);
documentBody.Append(titleParagraphe);
document.MainDocumentPart.Document.Save();
document.Dispose();
and the result is open*packaging*conventions without space between words
can some one help me please?!
You're on good way by handling the Space property, but you need to do it like this:
t = new Text()
{
Text = "your text with spaces ",
Space = SpaceProcessingModeValues.Preserve
};
Here is another way to set the attribute Space that can be used to specify SpaceProcessingMode.
t = new Text("This is some text");
t.Space = SpaceProcessingModeValues.Preserve;
The default of the attribute is SpaceProcessingModeValues.Default.
From API Documentation:
<w:r>
<w:t> significant whitespace </w:t>
</w:r>
Although there are three spaces on each side of the text content in the run, that whitespace has not been specifically marked as significant, therefore it is subject to the space preservation rules currently specified in that run's scope. end example]
The possible values for this attribute are defined by ยง2.10 of the XML 1.0 specification.

Resources