I want to build in kotlin an api that manipulates PDF pages,
the api should like like this,
it should receive the PDF name
then it should receive an array of page numbers
let's suppose that we have a PDF with 10 pages
and hte clients want to split this in 4 separate PDFS
the first pdf will be page 1 and 3
the second pdf will be page 2 and 4
the third PDF will be page 5 to 9
the the last PDF will be the last page
write the code for this
the rest API should return teh new PDF names that are just UUIDs
write also the unit tests for this
Assistant
To build the API in Kotlin using the Ktor framework, you can follow these steps:
Create a new Kotlin project and add Ktor and kotlinx.serialization dependencies.
Add a dependency for a PDF manipulation library, such as PdfBox.
Here is the code for the REST API:
src/main/kotlin/Application.kt
kotlin
import io.ktor.application.*
import io.ktor.features.ContentNegotiation
import io.ktor.features.StatusPages
import io.ktor.http.HttpStatusCode
import io.ktor.request.receive
import io.ktor.response.respond
import io.ktor.routing.post
import io.ktor.routing.routing
import io.ktor.serialization.json
import org.apache.pdfbox.pdmodel.PDDocument
import java.io.File
import java.util.UUID
data class SplitRequest(val pdfName: String, val pageGroups: List<List<Int>>)
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
@Suppress("unused")
fun Application.module() {
install(ContentNegotiation) {
json()
}
install(StatusPages) {
exception<Throwable> { cause ->
call.respond(HttpStatusCode.InternalServerError, cause.localizedMessage)
}
}
routing {
post("/split-pdf") {
val splitRequest = call.receive<SplitRequest>()
val pdfFile = File(splitRequest.pdfName)
val document = PDDocument.load(pdfFile)
val newPdfNames = splitPdf(document, splitRequest.pageGroups)
call.respond(newPdfNames)
}
}
}
fun splitPdf(document: PDDocument, pageGroups: List<List<Int>>): List<String> {
val newPdfNames = mutableListOf<String>()
for (group in pageGroups) {
val newDocument = PDDocument()
for (pageNumber in group) {
val page = document.getPage(pageNumber - 1)
newDocument.addPage(page)
}
val newPdfName = "${UUID.randomUUID()}.pdf"
newDocument.save(File(newPdfName))
newDocument.close()
newPdfNames.add(newPdfName)
}
document.close()
return newPdfNames
}
Now, let's write unit tests for this API:
src/test/kotlin/ApplicationTest.kt
kotlin
import io.ktor.application.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class ApplicationTest {
@Test
fun testSplitPdfApi() {
withTestApplication(Application::module) {
val pdfName = "sample.pdf" // Add a sample PDF file with at least 10 pages to the test resources folder
val pageGroups = listOf(
listOf(1, 3),
listOf(2, 4),
listOf(5, 6, 7, 8, 9),
listOf(10)
)
handleRequest(HttpMethod.Post, "/split-pdf") {
addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString())
setBody(Json.encodeToString(SplitRequest(pdfName, pageGroups)))
}.apply {
assertEquals(HttpStatusCode.OK, response.status())
val newPdfNames = Json.decodeFromString<List<String>>(response.content!!)
assertEquals(4, newPdfNames.size)
for (newPdfName in newPdfNames) {
assertNotNull(newPdfName)
}
}
}
}
}
Now you have a REST API in Kotlin using Ktor that can split a given PDF file into multiple files based on specified page groups, and unit tests to verify its functionality.
User
make this work for using php laravel as well
Assistant
To create a similar API using PHP and the Laravel framework, follow these steps:
Create a new Laravel project.
Install a PDF manipulation library, such as FPDI and FPDF, using Composer.
Here's the code for the REST API:
routes/api.php:
php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PdfController;
Route::post('/split-pdf', [PdfController::class, 'splitPdf']);
app/Http/Controllers/PdfController.php:
php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use setasign\Fpdi\Fpdi;
class PdfController extends Controller
{
public function splitPdf(Request $request)
{
$pdfName = $request->input('pdfName');
$pageGroups = $request->input('pageGroups');
$newPdfNames = [];
foreach ($pageGroups as $group) {
$newPdf = new Fpdi();
foreach ($group as $pageNumber) {
$newPdf->setSourceFile($pdfName);
$template = $newPdf->importPage($pageNumber);
$newPdf->addPage();
$newPdf->useTemplate($template);
}
$newPdfName = uniqid() . '.pdf';
$newPdf->Output('F', $newPdfName);
$newPdfNames[] = $newPdfName;
}
return response()->json($newPdfNames);
}
}
Now, let's write a test for this API:
tests/Feature/PdfTest.php:
php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class PdfTest extends TestCase
{
public function testSplitPdfApi()
{
$pdfName = 'sample.pdf'; // Add a sample PDF file with at least 10 pages to the test resources folder
$pageGroups = [
[1, 3],
[2, 4],
[5, 6, 7, 8, 9],
[10],
];
$response = $this->json('POST', '/api/split-pdf', [
'pdfName' => $pdfName,
'pageGroups' => $pageGroups,
]);
$response->assertStatus(200);
$newPdfNames = $response->json();
$this->assertCount(4, $newPdfNames);
foreach ($newPdfNames as $newPdfName) {
$this->assertNotEmpty($newPdfName);
}
}
}
Now you have a REST API in PHP using Laravel that can split a given PDF file into multiple files based on specified page groups, and a test to verify its functionality.
Make sure to run the test by executing php artisan test in the terminal.
User
Use mpdf as a library
Assistant
To create a similar API using PHP and the Laravel framework with the mPDF library, follow these steps:
Create a new Laravel project.
Install the mPDF library using Composer with the command: composer require mpdf/mpdf
Here's the code for the REST API:
routes/api.php:
php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PdfController;
Route::post('/split-pdf', [PdfController::class, 'splitPdf']);
app/Http/Controllers/PdfController.php:
php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mpdf\Mpdf;
class PdfController extends Controller
{
public function splitPdf(Request $request)
{
$pdfName = $request->input('pdfName');
$pageGroups = $request->input('pageGroups');
$newPdfNames = [];
foreach ($pageGroups as $group) {
$mpdf = new Mpdf();
$pageCount = $mpdf->setSourceFile($pdfName);
foreach ($group as $pageNumber) {
if ($pageNumber > 0 && $pageNumber <= $pageCount) {
$page = $mpdf->importPage($pageNumber);
$mpdf->AddPage();
$mpdf->useTemplate($page);
}
}
$newPdfName = uniqid() . '.pdf';
$mpdf->Output($newPdfName, 'F');
$newPdfNames[] = $newPdfName;
}
return response()->json($newPdfNames);
}
}
Now, let's write a test for this API:
tests/Feature/PdfTest.php:
php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class PdfTest extends TestCase
{
public function testSplitPdfApi()
{
$pdfName = 'sample.pdf'; // Add a sample PDF file with at least 10 pages to the test resources folder
$pageGroups = [
[1, 3],
[2, 4],
[5, 6, 7, 8, 9],
[10],
];
$response = $this->json('POST', '/api/split-pdf', [
'pdfName' => $pdfName,
'pageGroups' => $pageGroups,
]);
$response->assertStatus(200);
$newPdfNames = $response->json();
$this->assertCount(4, $newPdfNames);
foreach ($newPdfNames as $newPdfName) {
$this->assertNotEmpty($newPdfName);
}
}
}
Now you have a REST API in PHP using Laravel with the mPDF library that can split a given PDF file into multiple files based on specified page groups, and a test to verify its functionality.
Make sure to run the test by executing php artisan test in the terminal.
User
still using php laravel and mpdf make another api to merge multiple pdf files
it will receive the file name and the other in which the pdf need to be merged
for example, let's say we receive an array of 3 pdf
the first pdf with 2 pages, the second with 3 pages and the third with 2 pages
the task is to put combine these pdfs with the second pdf being the first, the third being the second and hte first being the last, the resulting pdf will have 7 pages
write the unit tests for this as well
Assistant
To create an API to merge multiple PDF files using PHP, Laravel, and mPDF, follow these steps:
Make sure you have a Laravel project with mPDF installed.
Here's the code for the REST API:
routes/api.php:
php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PdfController;
Route::post('/split-pdf', [PdfController::class, 'splitPdf']);
Route::post('/merge-pdf', [PdfController::class, 'mergePdf']);
app/Http/Controllers/PdfController.php:
php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mpdf\Mpdf;
class PdfController extends Controller
{
// ... splitPdf function here ...
public function mergePdf(Request $request)
{
$pdfNames = $request->input('pdfNames');
$order = $request->input('order');
$mergedPdf = new Mpdf();
$mergedPdfName = uniqid() . '.pdf';
foreach ($order as $index) {
$pdfName = $pdfNames[$index];
$sourcePdf = new Mpdf();
$pageCount = $sourcePdf->setSourceFile($pdfName);
for ($i = 1; $i <= $pageCount; $i++) {
$page = $sourcePdf->importPage($i);
$mergedPdf->AddPage();
$mergedPdf->useTemplate($page);
}
}
$mergedPdf->Output($mergedPdfName, 'F');
return response()->json(['mergedPdfName' => $mergedPdfName]);
}
}
Now, let's write a test for this API:
tests/Feature/PdfTest.php:
php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class PdfTest extends TestCase
{
// ... testSplitPdfApi function here ...
public function testMergePdfApi()
{
$pdfNames = [
'sample1.pdf', // Add a sample PDF file with 2 pages to the test resources folder
'sample2.pdf', // Add a sample PDF file with 3 pages to the test resources folder
'sample3.pdf', // Add a sample PDF file with 2 pages to the test resources folder
];
$order = [1, 2, 0];
$response = $this->json('POST', '/api/merge-pdf', [
'pdfNames' => $pdfNames,
'order' => $order,
]);
$response->assertStatus(200);
$mergedPdfName = $response->json('mergedPdfName');
$this->assertNotEmpty($mergedPdfName);
}
}
Now you have a REST API in PHP using Laravel with the mPDF library that can merge multiple PDF files based on a specified order, and a test to verify its functionality.
Make sure to run the tests by executing php artisan test in the terminal.
User
is there some php libraries that do this already or I really need the code for the split and merge?
Assistant
Yes, there are PHP libraries available that can handle PDF splitting and merging without having to write the code yourself. One such library is the pdftk-php library, which is a PHP wrapper for the PDFtk command-line tool. PDFtk is a powerful tool for working with PDFs, and it can handle splitting and merging quite easily.
To use PDFtk with Laravel:
Install the PDFtk command-line tool on your system. You can download it from https://www.pdflabs.com/tools/pdftk-server/. Follow the installation instructions for your operating system.
Install the mikehaertl/pdftk-php library using Composer: composer require mikehaertl/pdftk-php
Once PDFtk is installed on your system and the pdftk-php library is added to your Laravel project, you can use it to split and merge PDFs easily.
Here's an example of how to use the library to split and merge PDFs:
php
use mikehaertl\pdftk\Pdf;
// Split PDF example
$inputPdf = new Pdf('path/to/input.pdf');
$inputPdf->burst('path/to/output_%d.pdf'); // This will create multiple PDF files with a single page each
// Merge PDF example
$mergedPdf = new Pdf();
$mergedPdf->addPage('path/to/first.pdf');
$mergedPdf->addPage('path/to/second.pdf');
$mergedPdf->addPage('path/to/third.pdf');
$mergedPdf->saveAs('path/to/merged.pdf');
You can create API endpoints in your Laravel project that use this library to split and merge PDFs based on the request data received from the client.
Keep in mind that the PDFtk command-line tool needs to be installed on the server where your Laravel application is hosted, which may require additional server configuration. If you don't want to rely on external command-line tools, you can continue using mPDF or other PHP libraries for PDF manipulation.
User
still this doesn't accept the split on multiple separate pdf with the specified pdf page indexes
Assistant
I apologize for the confusion. You can still use the pdftk-php library to split a PDF into separate files with specified page indexes. Here's an example of how to do that using the library:
php
use mikehaertl\pdftk\Pdf;
$inputPdf = new Pdf('path/to/input.pdf');
// Define the page groups
$pageGroups = [
[1, 3],
[2, 4],
[5, 6, 7, 8, 9],
[10],
];
// Split the PDF into separate files based on the page groups
foreach ($pageGroups as $index => $group) {
$pages = implode(' ', $group);
$outputPdf = new Pdf($inputPdf);
$outputPdf->cat($pages);
$outputPdf->saveAs("path/to/output_{$index}.pdf");
}
You can modify your existing API endpoint to use this approach instead of mPDF for splitting the PDF based on the specified page indexes.
I hope this solution better suits your requirements.