added hello world script and dotted for create dotted A4 for print

This commit is contained in:
2026-05-08 10:57:36 +02:00
parent fc2fee30cc
commit a67f5ead68
6 changed files with 564 additions and 0 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
/vendor /vendor
/output

70
AGENTS.md Normal file
View File

@ -0,0 +1,70 @@
# Repository Guidelines
## Project Structure & Module Organization
This is a small PHP Composer project for generating PDF files with `tecnickcom/tc-lib-pdf`.
- `src/` contains executable PDF scripts.
- `src/hello-world.php` is a minimal PDF example.
- `src/dotted.php` generates A4 dotted technical drawing paper.
- `output/` contains generated PDFs such as `output/dotted.pdf`; it is ignored by Git.
- `vendor/` contains Composer dependencies and generated font assets; it is ignored by Git.
- `README.md` documents setup and user-facing commands.
There is currently no dedicated `tests/` directory.
## Build, Test, and Development Commands
Install project dependencies:
```powershell
composer install
```
Generate font definitions required by `tc-lib-pdf-font`:
```powershell
cd vendor\tecnickcom\tc-lib-pdf-font\util
composer install
cd ..
composer install
cd util
php bulk_convert.php
```
Check PHP syntax:
```powershell
php -l src\hello-world.php
php -l src\dotted.php
```
Generate dotted paper from CLI:
```powershell
php src\dotted.php --dot-size=0.4 --space=5
```
Open via web server:
```text
http://localhost/pdfcreator/src/dotted.php?dot-size=0.4&space=5
```
## Coding Style & Naming Conventions
Use PHP 8 syntax and keep scripts under the `Igor\Pdfcreator` namespace. Prefer clear helper functions for parameter parsing, validation, and PDF drawing. Use four-space indentation, strict readable variable names like `$pageWidth`, `$tableBox`, and `$dotSize`, and kebab-case filenames for browser-facing scripts, for example `hello-world.php`.
Avoid writing generated files into tracked paths. Keep `vendor/` and `output/` uncommitted.
## Testing Guidelines
No automated test suite is configured yet. For changes, at minimum run `php -l` on modified PHP files and execute the affected script from CLI. For `src/dotted.php`, verify valid parameters generate `output/dotted.pdf` and invalid values such as `--dot-size=0` or `--space=1` fail with an error.
## Commit & Pull Request Guidelines
Git history was not available in this environment, so use concise imperative commit messages such as `Add dotted paper generator` or `Update font setup docs`. Pull requests should describe the change, list commands run, mention generated output paths, and include screenshots or PDFs when visual PDF layout changes.
## Security & Configuration Tips
Do not commit generated PDFs, Composer vendor files, or local configuration. Keep web scripts free of output before PDF headers. Validate all CLI and query parameters before using them in PDF generation.

179
README.md Normal file
View File

@ -0,0 +1,179 @@
# pdfCreator
Projekt na generovanie PDF suborov pomocou `tecnickcom/tc-lib-pdf`.
## Slovensky
### Inicializacia po cistom clone
Po novom clone repozitara alebo po zmazani adresara `vendor` najprv nainstaluj hlavne Composer zavislosti:
```powershell
composer install
```
Samotny `composer install` nevygeneruje PDF font definicie, ktore `tc-lib-pdf-font` nacitava pri renderovani. Bez nich moze aplikacia spadnut napr. s chybou:
```text
unable to read file: helvetica.json
```
Fonty vygeneruj cez utilitny balicek v `vendor/tecnickcom/tc-lib-pdf-font`:
```powershell
cd vendor\tecnickcom\tc-lib-pdf-font\util
composer install
cd ..
composer install
cd util
php bulk_convert.php
```
Po uspesnom behu by mal existovat napr. subor:
```text
vendor\tecnickcom\tc-lib-pdf-font\target\fonts\core\helvetica.json
```
### Skripty
Hello world PDF:
```powershell
php src\hello-world.php
```
Bodkovany papier pre technicke nacrtky:
```powershell
php src\dotted.php
```
Volitelne parametre bodkovaneho papiera:
```powershell
php src\dotted.php --dot-size=0.4 --space=5
```
Vystup z CLI sa ulozi do:
```text
output\dotted.pdf
```
### Web spustenie
Hello world PDF:
```text
http://localhost/pdfcreator/src/hello-world.php
```
Bodkovany papier inline v prehliadaci:
```text
http://localhost/pdfcreator/src/dotted.php?dot-size=0.4&space=5
```
### Overenie
Syntax PHP skriptov:
```powershell
php -l src\hello-world.php
php -l src\dotted.php
```
### Poznamka k `vendor` a `output`
Adresare `vendor` a `output` su ignorovane v Gite. Ak sa `vendor` zmaze alebo sa projekt inicializuje na inom stroji, treba instalaciu zavislosti a generovanie fontov zopakovat.
## English
### Fresh Repository Setup
After cloning the repository, or after deleting the `vendor` directory, install the main Composer dependencies first:
```powershell
composer install
```
The root `composer install` does not generate the PDF font definition files used by `tc-lib-pdf-font` at runtime. Without them, the application may fail with an error such as:
```text
unable to read file: helvetica.json
```
Generate the fonts through the utility package inside `vendor/tecnickcom/tc-lib-pdf-font`:
```powershell
cd vendor\tecnickcom\tc-lib-pdf-font\util
composer install
cd ..
composer install
cd util
php bulk_convert.php
```
After a successful run, this file should exist:
```text
vendor\tecnickcom\tc-lib-pdf-font\target\fonts\core\helvetica.json
```
### Scripts
Hello world PDF:
```powershell
php src\hello-world.php
```
Dotted paper for technical sketches:
```powershell
php src\dotted.php
```
Optional dotted paper parameters:
```powershell
php src\dotted.php --dot-size=0.4 --space=5
```
CLI output is saved to:
```text
output\dotted.pdf
```
### Web Usage
Hello world PDF:
```text
http://localhost/pdfcreator/src/hello-world.php
```
Dotted paper rendered inline in the browser:
```text
http://localhost/pdfcreator/src/dotted.php?dot-size=0.4&space=5
```
### Verification
Check PHP syntax:
```powershell
php -l src\hello-world.php
php -l src\dotted.php
```
### Notes About `vendor` and `output`
The `vendor` and `output` directories are ignored by Git. If `vendor` is deleted or the project is initialized on another machine, repeat the dependency installation and font generation steps.

BIN
output/dotted.pdf Normal file

Binary file not shown.

287
src/dotted.php Normal file
View File

@ -0,0 +1,287 @@
<?php
namespace Igor\Pdfcreator;
require __DIR__ . '/../vendor/autoload.php';
\define('K_PATH_FONTS', \realpath(__DIR__ . '/../vendor/tecnickcom/tc-lib-pdf-font/target/fonts'));
$pdf = new \Com\Tecnick\Pdf\Tcpdf();
/**
* @return array{dot-size: float, space: float}
*/
function readParams(): array
{
if (PHP_SAPI === 'cli') {
$options = \getopt('', ['dot-size:', 'space:']);
return [
'dot-size' => parseFloatParam($options['dot-size'] ?? null, 0.35),
'space' => parseFloatParam($options['space'] ?? null, 5.0),
];
}
return [
'dot-size' => parseFloatParam($_GET['dot-size'] ?? null, 0.35),
'space' => parseFloatParam($_GET['space'] ?? null, 5.0),
];
}
function parseFloatParam(mixed $value, float $default): float
{
if ($value === null || $value === '') {
return $default;
}
if (\is_array($value)) {
fail('Parameter value must be a single number.');
}
$normalized = \str_replace(',', '.', (string) $value);
if (! \is_numeric($normalized)) {
fail('Parameter value must be numeric.');
}
return (float) $normalized;
}
/**
* @param array{dot-size: float, space: float} $params
*/
function validateParams(array $params): void
{
if ($params['dot-size'] <= 0 || $params['dot-size'] > 2) {
fail('Invalid --dot-size value. Use a number greater than 0 and at most 2 mm.');
}
if ($params['space'] < 2 || $params['space'] > 20) {
fail('Invalid --space value. Use a number from 2 to 20 mm.');
}
}
function fail(string $message): never
{
if (PHP_SAPI === 'cli') {
\fwrite(STDERR, 'Error: ' . $message . PHP_EOL);
exit(1);
}
\http_response_code(400);
\header('Content-Type: text/plain; charset=utf-8');
echo 'Error: ' . $message;
exit;
}
function getLineStyle(float $width, string $color): array
{
return [
'lineWidth' => $width,
'lineCap' => 'butt',
'lineJoin' => 'miter',
'dashArray' => [],
'dashPhase' => 0,
'lineColor' => $color,
];
}
function getFillStyle(string $color): array
{
return [
'all' => [
'lineWidth' => 0,
'lineCap' => 'butt',
'lineJoin' => 'miter',
'dashArray' => [],
'dashPhase' => 0,
'lineColor' => $color,
'fillColor' => $color,
],
];
}
/**
* @param array{x: float, y: float, width: float, height: float} $tableBox
*/
function drawDotGrid(
\Com\Tecnick\Pdf\Tcpdf $pdf,
float $left,
float $top,
float $right,
float $bottom,
float $dotSize,
float $space,
array $tableBox
): void {
$radius = $dotSize / 2.0;
$dotStyle = getFillStyle('rgb(145,145,145)');
for ($y = $top; $y <= $bottom; $y += $space) {
for ($x = $left; $x <= $right; $x += $space) {
$insideTable = (
$x >= $tableBox['x']
&& $x <= ($tableBox['x'] + $tableBox['width'])
&& $y >= $tableBox['y']
&& $y <= ($tableBox['y'] + $tableBox['height'])
);
if ($insideTable) {
continue;
}
$pdf->page->addContent($pdf->graph->getCircle($x, $y, $radius, 0, 360, 'F', $dotStyle));
}
}
}
function drawFrame(\Com\Tecnick\Pdf\Tcpdf $pdf, float $pageWidth, float $pageHeight): void
{
$outerMargin = 5.0;
$pdf->page->addContent(
$pdf->graph->getRect(
$outerMargin,
$outerMargin,
$pageWidth - (2 * $outerMargin),
$pageHeight - (2 * $outerMargin),
'D',
['all' => getLineStyle(0.18, 'black')]
)
);
}
/**
* @param array{x: float, y: float, width: float, height: float} $tableBox
*/
function drawTitleBlock(\Com\Tecnick\Pdf\Tcpdf $pdf, array $tableBox): void
{
assertFontIsAvailable();
$font = $pdf->font->insert($pdf->pon, 'helvetica', '', 7.0, 0.0, 1.0);
$pdf->page->addContent($font['out']);
$pdf->page->addContent($pdf->color->getPdfColor('black'));
$lineStyle = getLineStyle(0.16, 'black');
$rowHeight = $tableBox['height'] / 4.0;
$labelWidth = 28.0;
$pdf->page->addContent(
$pdf->graph->getRect($tableBox['x'], $tableBox['y'], $tableBox['width'], $tableBox['height'], 'D', [
'all' => $lineStyle,
])
);
for ($row = 1; $row < 4; ++$row) {
$lineY = $tableBox['y'] + ($row * $rowHeight);
$pdf->page->addContent(
$pdf->graph->getLine($tableBox['x'], $lineY, $tableBox['x'] + $tableBox['width'], $lineY, $lineStyle)
);
}
$pdf->page->addContent(
$pdf->graph->getLine(
$tableBox['x'] + $labelWidth,
$tableBox['y'],
$tableBox['x'] + $labelWidth,
$tableBox['y'] + $tableBox['height'],
$lineStyle
)
);
$labels = ['Názov projektu', 'Autor', 'Dátum', 'Revízia'];
foreach ($labels as $index => $label) {
$pdf->page->addContent(
$pdf->getTextCell(
$label,
$tableBox['x'] + 2.0,
$tableBox['y'] + ($index * $rowHeight) + 2.7,
$labelWidth - 4.0,
4.0,
valign: 'C',
halign: 'L',
drawcell: false
)
);
}
}
function assertFontIsAvailable(): void
{
$fontFile = K_PATH_FONTS . DIRECTORY_SEPARATOR . 'core' . DIRECTORY_SEPARATOR . 'helvetica.json';
if (! \is_readable($fontFile)) {
fail(
'Missing font file helvetica.json. Generate fonts first: '
. 'cd vendor\\tecnickcom\\tc-lib-pdf-font\\util && composer install && cd .. && composer install '
. '&& cd util && php bulk_convert.php'
);
}
}
/**
* @param array{dot-size: float, space: float} $params
*/
function buildPdf(\Com\Tecnick\Pdf\Tcpdf $pdf, array $params): string
{
$pageWidth = 210.0;
$pageHeight = 297.0;
$innerMargin = 10.0;
$tableBox = [
'width' => 80.0,
'height' => 40.0,
'x' => $pageWidth - $innerMargin - 80.0,
'y' => $pageHeight - $innerMargin - 40.0,
];
$pdf->setCreator('pdfCreator');
$pdf->setAuthor('');
$pdf->setSubject('Dotted technical drawing paper');
$pdf->setTitle('Dotted technical drawing paper');
$pdf->setKeywords('PDF dotted grid technical drawing floor plan');
$pdf->setPDFFilename('dotted.pdf');
$pdf->addPage(['format' => 'A4', 'orientation' => 'P']);
drawFrame($pdf, $pageWidth, $pageHeight);
drawDotGrid(
$pdf,
$innerMargin,
$innerMargin,
$pageWidth - $innerMargin,
$pageHeight - $innerMargin,
$params['dot-size'],
$params['space'],
$tableBox
);
drawTitleBlock($pdf, $tableBox);
return $pdf->getOutPDFString();
}
function outputPdf(\Com\Tecnick\Pdf\Tcpdf $pdf, string $rawPdf): void
{
if (PHP_SAPI !== 'cli') {
if (\ob_get_length() !== false && \ob_get_length() > 0) {
\ob_clean();
}
$pdf->renderPDF($rawPdf);
return;
}
$outputDir = \dirname(__DIR__) . DIRECTORY_SEPARATOR . 'output';
if (! \is_dir($outputDir) && ! \mkdir($outputDir, 0775, true) && ! \is_dir($outputDir)) {
fail('Unable to create output directory: ' . $outputDir);
}
$outputFile = $outputDir . DIRECTORY_SEPARATOR . 'dotted.pdf';
if (\file_put_contents($outputFile, $rawPdf) === false) {
fail('Unable to write PDF file: ' . $outputFile);
}
echo 'PDF generated: ' . $outputFile . PHP_EOL;
}
$params = readParams();
validateParams($params);
$rawPdf = buildPdf($pdf, $params);
outputPdf($pdf, $rawPdf);

27
src/hello-world.php Normal file
View File

@ -0,0 +1,27 @@
<?php
namespace Igor\Pdfcreator;
require __DIR__.'/../vendor/autoload.php';
\define('K_PATH_FONTS', \realpath(__DIR__ . '/../vendor/tecnickcom/tc-lib-pdf-font/target/fonts'));
$pdf = new \Com\Tecnick\Pdf\Tcpdf();
$bfont = $pdf->font->insert($pdf->pon, 'helvetica', '', 12);
$page = $pdf->addPage();
$pdf->page->addContent($bfont['out']);
$html = '<h1>Hello, PDF!</h1><p>Generated with tc-lib-pdf.</p>';
$pdf->addHTMLCell(
html: $html,
posx: 15, // mm from left page edge
posy: 20, // mm from top page edge
width: 180, // mm wide (0 = to right margin)
);
$rawpdf = $pdf->getOutPDFString();
$pdf->renderPDF($rawpdf);