React'te HTML'den PDF'ye Dönüşüm (Geliştirici Eğitimi)
React'te HTML'yi PDF'e Dönüştürme
React'te HTML'yi PDF'e dönüştürmek, birçok web uygulaması için önemli bir özellik haline geldi. İster bir faturalama sistemi, ister rapor üreticisi oluşturuyor olun ya da yalnızca evrensel kabul gören bir formatta bilgi paylaşmanız gerekiyorsa, PDF oluşturma hayati önem taşır. Bu makalede, HTML'yi PDF'e dönüştürerek React uygulamanızda PDF dosyalarını nasıl oluşturacağınızı ve biçimlendireceğinizi keşfedeceğiz.
React'te HTML'yi PDF'e Dönüştürme
- Bir React projesi oluşturun ve yapılandırın
- npm kullanarak React'te HTML'yi PDF'e dönüştürmek için kütüphaneyi indirin
- React-pdf/renderer'dan gerekli modülleri içe aktarın
- İçe aktarılan modüllerle HTML sayfasını yapılandırın
- PDFDownloadLink modülünü kullanarak React-pdf'un HTML'yi PDF'e dönüştürmesini kullanın
PDF Oluşturma İçin Popüler Kütüphaneler
HTML'yi PDF'e dönüştürme işlemine başlamadan önce, React uygulamalarınızda PDF oluşturma için kullanılan bazı popüler kütüphaneleri tartışalım:
- React-pdf: React uygulamalarında PDF belgeleri oluşturmak için güçlü bir kütüphane. Çeşitli stil seçeneklerini destekler ve kolaylıkla karmaşık, çok sayfalı PDF'ler oluşturabilir.
- jsPDF: Anında PDF dosyaları oluşturmak için yaygın olarak kullanılan bir JavaScript kütüphanesi. Metin stilizasyonu, görüntü yerleştirme ve daha fazlası dahil olmak üzere geniş bir özellik yelpazesi sunar.
- html2canvas: Bu kütüphane, bir HTML elemanının ekran görüntüsünü yakalamanıza ve ardından bu ekran görüntüsünü jsPDF gibi diğer kütüphanelerle PDF'e dönüştürebileceğiniz bir tuval objesine dönüştürmenize olanak tanır.
React'te HTML'yi PDF'e Dönüştürme İçin Ön Koşullar
React ve ekosistemine aşinalık
HTML'yi PDF'e dönüştürmeye girişmeden önce, React'ı tam anlamıyla anlamak esastır. Bu, JSX, state yönetimi, bileşen yaşam döngüleri ve hook'ları hakkında bilgi sahibi olmayı içerir.
HTML, CSS ve JavaScript Anlayışı
React-pdf kütüphanesi ile çalışmak için HTML, CSS ve JavaScript'te sağlam bir temel gereklidir. Bu, HTML etiketleri ve öznitelikleri, CSS stil ve seçicileri ve değişkenler, fonksiyonlar ve döngüler gibi JavaScript temellerine dair bilgi sahibi olmayı içerir.
Bir React Uygulamasına Başlarken
HTML'yi PDF'ye React'te dönüştürmeye geçmeden önce, popüler create-react-app CLI aracını kullanarak yeni bir React uygulaması nasıl oluşturulur, hızlıca gözden geçirelim. Bu, PDF oluşturma örneğimizin temeli olarak hizmet verecek.
Adım 1 Node.js Yükleme
Makinenizde Node.js yüklü olduğundan emin olun. Node.js'nin en son sürümünü resmi Node.js web sitesinden indirebilirsiniz.
Adım 2 create-react-app Yükleme
create-react-app, React uygulamaları oluşturmak için yaygın olarak kullanılan bir CLI aracıdır. Aşağıdaki komutu kullanarak küresel olarak yükleyin:
npm install -g create-react-appnpm install -g create-react-appAdım 3 Yeni Bir React Uygulaması Oluşturma
Artık create-react-app'i yüklemiş olduğunuza göre, aşağıdaki komutla yeni bir React uygulaması oluşturabilirsiniz:
create-react-app my-pdf-appcreate-react-app my-pdf-appBu komut, my-pdf-app adlı bir klasörde yeni bir React uygulaması oluşturacak. Yeni oluşturulan dizine geçin:
cd my-pdf-appcd my-pdf-appAdım 4 Geliştirme Sunucusunu Başlatma
Geliştirme sunucusunu çalıştırmak ve yeni React uygulamanızı görmek için aşağıdaki komutu çalıştırın:
npm startnpm startAdım 5 PDF Oluşturmayı Uygulama
Artık bir React uygulaması kurduğunuza göre, bu makalenin önceki bölümlerinde belirtilen adımları izleyerek popüler kütüphaneleri kullanarak HTML'yi PDF'e çevirme işlemini uygulayabilirsiniz.
React-pdf Kütüphanesini Tanıtma
React-pdf, React uygulamaları için tasarlanmış popüler bir kütüphane olup, React ekosistemiyle sorunsuz entegrasyon sağlar. Bazı temel özellikleri arasında gömülü ve harici CSS desteği, çok sayfalı PDF oluşturma, gelişmiş stil özellikleri ve sunucu tarafı işleme (SSR) uyumluluğu yer alır.
React-pdf ile PDF Dosyaları Oluşturma
Bu bölümde, bir React uygulamasında PDF dosyalarını oluşturmak için React-pdf kullanmaya odaklanacağız. React-pdf paketini kurarak başlayın:
npm install --save @react-pdf/renderernpm install --save @react-pdf/rendererKurulduktan sonra, PDF belgenizin yapısını tanımlamak için yeni bir React bileşeni oluşturabilirsiniz:
import React from 'react';
import {
Document,
Page,
Text,
View,
StyleSheet
} from '@react-pdf/renderer';
// Sample invoice data
const invoiceData = {
sender: {
name: "John Doe",
address: "123 Main Street",
city: "New York",
state: "NY",
zip: "10001",
},
recipient: {
name: "Jane Smith",
address: "456 Elm Street",
city: "San Francisco",
state: "CA",
zip: "94107",
},
items: [
{ description: "Item 1", quantity: 2, unitPrice: 10 },
{ description: "Item 2", quantity: 3, unitPrice: 15 },
{ description: "Item 3", quantity: 1, unitPrice: 20 },
],
invoiceNumber: "INV-123456",
date: "April 26, 2023",
};
// Define styles for PDF document
const styles = StyleSheet.create({
page: {
backgroundColor: "#FFF",
padding: 30,
},
header: {
fontSize: 24,
textAlign: "center",
marginBottom: 30,
},
sender: {
marginBottom: 20,
},
recipient: {
marginBottom: 30,
},
addressLine: {
fontSize: 12,
marginBottom: 2,
},
itemsTable: {
display: "table",
width: "100%",
borderStyle: "solid",
borderWidth: 1,
borderRightWidth: 0,
borderBottomWidth: 0,
},
tableRow: {
margin: "auto",
flexDirection: "row",
},
tableColHeader: {
width: "25%",
borderStyle: "solid",
borderWidth: 1,
borderLeftWidth: 0,
borderTopWidth: 0,
backgroundColor: "#F0F0F0",
},
tableCol: {
width: "25%",
borderStyle: "solid",
borderWidth: 1,
borderLeftWidth: 0,
borderTopWidth: 0,
},
tableCell: {
fontSize: 12,
textAlign: "center",
padding: 5,
},
total: {
marginTop: 20,
textAlign: "right",
},
totalLabel: {
fontSize: 14,
fontWeight: "bold",
},
totalValue: {
fontSize: 14,
},
});
const InvoiceDocument = () => {
// Calculate total amount
const totalAmount = invoiceData.items.reduce(
(total, item) => total + item.quantity * item.unitPrice,
0
);
return (
<Document>
<Page style={styles.page}>
<Text style={styles.header}>Invoice</Text>
<View style={styles.sender}>
<Text>{invoiceData.sender.name}</Text>
<Text>{invoiceData.sender.address}</Text>
<Text>
{invoiceData.sender.city}, {invoiceData.sender.state} {invoiceData.sender.zip}
</Text>
</View>
<View style={styles.recipient}>
<Text>{invoiceData.recipient.name}</Text>
<Text>{invoiceData.recipient.address}</Text>
<Text>
{invoiceData.recipient.city}, {invoiceData.recipient.state} {invoiceData.recipient.zip}
</Text>
</View>
<View style={styles.itemsTable}>
<View style={styles.tableRow}>
<Text style={[styles.tableColHeader, styles.tableCell]}>Description</Text>
<Text style={[styles.tableColHeader, styles.tableCell]}>Quantity</Text>
<Text style={[styles.tableColHeader, styles.tableCell]}>Unit Price</Text>
<Text style={[styles.tableColHeader, styles.tableCell]}>Amount</Text>
</View>
{invoiceData.items.map((item, index) => (
<View key={index} style={styles.tableRow}>
<Text style={[styles.tableCol, styles.tableCell]}>{item.description}</Text>
<Text style={[styles.tableCol, styles.tableCell]}>{item.quantity}</Text>
<Text style={[styles.tableCol, styles.tableCell]}>{item.unitPrice.toFixed(2)}</Text>
<Text style={[styles.tableCol, styles.tableCell]}>
{(item.quantity * item.unitPrice).toFixed(2)}
</Text>
</View>
))}
</View>
<View style={styles.total}>
<Text style={styles.totalLabel}>Total: ${totalAmount.toFixed(2)}</Text>
</View>
</Page>
</Document>
);
};
export default InvoiceDocument;import React from 'react';
import {
Document,
Page,
Text,
View,
StyleSheet
} from '@react-pdf/renderer';
// Sample invoice data
const invoiceData = {
sender: {
name: "John Doe",
address: "123 Main Street",
city: "New York",
state: "NY",
zip: "10001",
},
recipient: {
name: "Jane Smith",
address: "456 Elm Street",
city: "San Francisco",
state: "CA",
zip: "94107",
},
items: [
{ description: "Item 1", quantity: 2, unitPrice: 10 },
{ description: "Item 2", quantity: 3, unitPrice: 15 },
{ description: "Item 3", quantity: 1, unitPrice: 20 },
],
invoiceNumber: "INV-123456",
date: "April 26, 2023",
};
// Define styles for PDF document
const styles = StyleSheet.create({
page: {
backgroundColor: "#FFF",
padding: 30,
},
header: {
fontSize: 24,
textAlign: "center",
marginBottom: 30,
},
sender: {
marginBottom: 20,
},
recipient: {
marginBottom: 30,
},
addressLine: {
fontSize: 12,
marginBottom: 2,
},
itemsTable: {
display: "table",
width: "100%",
borderStyle: "solid",
borderWidth: 1,
borderRightWidth: 0,
borderBottomWidth: 0,
},
tableRow: {
margin: "auto",
flexDirection: "row",
},
tableColHeader: {
width: "25%",
borderStyle: "solid",
borderWidth: 1,
borderLeftWidth: 0,
borderTopWidth: 0,
backgroundColor: "#F0F0F0",
},
tableCol: {
width: "25%",
borderStyle: "solid",
borderWidth: 1,
borderLeftWidth: 0,
borderTopWidth: 0,
},
tableCell: {
fontSize: 12,
textAlign: "center",
padding: 5,
},
total: {
marginTop: 20,
textAlign: "right",
},
totalLabel: {
fontSize: 14,
fontWeight: "bold",
},
totalValue: {
fontSize: 14,
},
});
const InvoiceDocument = () => {
// Calculate total amount
const totalAmount = invoiceData.items.reduce(
(total, item) => total + item.quantity * item.unitPrice,
0
);
return (
<Document>
<Page style={styles.page}>
<Text style={styles.header}>Invoice</Text>
<View style={styles.sender}>
<Text>{invoiceData.sender.name}</Text>
<Text>{invoiceData.sender.address}</Text>
<Text>
{invoiceData.sender.city}, {invoiceData.sender.state} {invoiceData.sender.zip}
</Text>
</View>
<View style={styles.recipient}>
<Text>{invoiceData.recipient.name}</Text>
<Text>{invoiceData.recipient.address}</Text>
<Text>
{invoiceData.recipient.city}, {invoiceData.recipient.state} {invoiceData.recipient.zip}
</Text>
</View>
<View style={styles.itemsTable}>
<View style={styles.tableRow}>
<Text style={[styles.tableColHeader, styles.tableCell]}>Description</Text>
<Text style={[styles.tableColHeader, styles.tableCell]}>Quantity</Text>
<Text style={[styles.tableColHeader, styles.tableCell]}>Unit Price</Text>
<Text style={[styles.tableColHeader, styles.tableCell]}>Amount</Text>
</View>
{invoiceData.items.map((item, index) => (
<View key={index} style={styles.tableRow}>
<Text style={[styles.tableCol, styles.tableCell]}>{item.description}</Text>
<Text style={[styles.tableCol, styles.tableCell]}>{item.quantity}</Text>
<Text style={[styles.tableCol, styles.tableCell]}>{item.unitPrice.toFixed(2)}</Text>
<Text style={[styles.tableCol, styles.tableCell]}>
{(item.quantity * item.unitPrice).toFixed(2)}
</Text>
</View>
))}
</View>
<View style={styles.total}>
<Text style={styles.totalLabel}>Total: ${totalAmount.toFixed(2)}</Text>
</View>
</Page>
</Document>
);
};
export default InvoiceDocument;Şimdi PDFDownloadLink bileşenini React-pdf üzerinden kullanarak oluşturulan PDF dosyasını indirebilirsiniz:
import React from 'react';
import { PDFDownloadLink } from '@react-pdf/renderer';
import InvoiceDocument from './InvoiceDocument';
import './App.css';
const App = () => (
<div className="app-container">
<PDFDownloadLink
document={<InvoiceDocument />}
fileName="invoice.pdf"
className="download-button"
>
{({ loading }) =>
loading ? 'Loading document...' : 'Download Invoice'
}
</PDFDownloadLink>
</div>
);
export default App;import React from 'react';
import { PDFDownloadLink } from '@react-pdf/renderer';
import InvoiceDocument from './InvoiceDocument';
import './App.css';
const App = () => (
<div className="app-container">
<PDFDownloadLink
document={<InvoiceDocument />}
fileName="invoice.pdf"
className="download-button"
>
{({ loading }) =>
loading ? 'Loading document...' : 'Download Invoice'
}
</PDFDownloadLink>
</div>
);
export default App;Özel bir kullanıcı arayüzü için App.css dosyasına bazı CSS stilleri ekleyin:
.app-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #d1e8ff;
}
.download-button {
display: inline-block;
background-color: #5a8fd5;
color: #fff;
font-size: 18px;
font-weight: bold;
padding: 12px 24px;
border-radius: 4px;
text-decoration: none;
cursor: pointer;
transition: background-color 0.3s ease;
}
.download-button:hover {
background-color: #3a68b7;
}localhost:3000 adresini tarayıcınızda açın. İndirme butonuna tıkladığınızda, PDF dosyası indirilecektir.
PDF Dosyalarınızı Stilize Etme
React-pdf kütüphanesi, CSS'e benzer geniş bir stil seçenekleri yelpazesi sunar. PDF dosyalarınızın görünümünü özelleştirmek için kullanabileceğiniz bazı yaygın stil özellikleri şunlardır:
color: Metin rengini ayarlar.fontSize: Metnin yazı boyutunu ayarlar.fontFamily: Metnin yazı tipini ayarlar.textAlign: Metin hizalamasını ayarlar (örneğin, 'sol', 'sağ', 'orta' veya 'iki yana yasla').margin: Bir elemanın etrafındaki kenar boşluğunu ayarlar.padding: Bir elemanın içindeki dolgu boşluğunu ayarlar.border: Bir elemanın etrafındaki kenarlığı ayarlar.backgroundColor: Bir elemanın arka plan rengini ayarlar.
React Geliştiricileri İçin Alternatif Bir PDF Kütüphanesi
IronPDF for Node.js, React'te HTML'yi PDF'e dönüştürmek için mükemmel bir alternatiftir. Iron Software tarafından geliştirilen, geliştiricilerin doğrudan Node.js uygulamalarından PDF belgeleri oluşturup manipüle etmelerini sağlayan güçlü bir kütüphanedir. Öne çıkan özelliklerinden biri, PDF oluşturma sürecinde HTML içeriğinde JavaScript yürütme yeteneği olup, dinamik ve etkileşimli PDF oluşturmaya olanak tanır.
Windows, MacOS, Linux, Docker ve Azure, AWS gibi bulut platformları dahil çeşitli platformlar için destek sunarak, IronPDF çapraz platform uyumluluğu sağlar. Kullanıcı dostu API'si, geliştiricilerin PDF oluşturma ve manipülasyonunu hızla Node.js projelerine entegre etmelerini sağlar.
React, kullanıcı arayüzleri oluşturmak için bir JavaScript kütüphanesi olup, IronPDF Node.js için geliştirilmiş olduğundan, onun Node.js API'sini kullanarak React uygulamalarınıza entegre edebilirsiniz.
İşte React ile IronPDF kullanmanın bir taslağı:
- IronPDF Kurulumu: IronPDF'i, projelerinize npm veya yarn ile kurabilirsiniz.
npm install @ironsoftware/ironpdfnpm install @ironsoftware/ironpdf- React Bileşenleri ile Entegrasyon: IronPDF'u kullanarak PDF oluşturma ve manipülasyonu gerçekleştiren React bileşenleri oluşturabilirsiniz. Örneğin, HTML içeriğini girdi olarak alan ve IronPDF'un API'si kullanarak bir PDF'e dönüştüren bir bileşene sahip olabilirsiniz.
import React from 'react';
import { PdfDocument } from '@ironsoftware/ironpdf';
const HTMLToPDFComponent = () => {
const convertHTMLToPDF = async (htmlContent) => {
try {
const pdf = await PdfDocument.fromHtml(htmlContent);
await pdf.saveAs('generated_pdf.pdf');
alert('PDF generated successfully!');
} catch (error) {
console.error('Error generating PDF:', error);
}
};
return (
<div>
{/* Input HTML content */}
<textarea onChange={(e) => convertHTMLToPDF(e.target.value)} />
</div>
);
};
export default HTMLToPDFComponent;import React from 'react';
import { PdfDocument } from '@ironsoftware/ironpdf';
const HTMLToPDFComponent = () => {
const convertHTMLToPDF = async (htmlContent) => {
try {
const pdf = await PdfDocument.fromHtml(htmlContent);
await pdf.saveAs('generated_pdf.pdf');
alert('PDF generated successfully!');
} catch (error) {
console.error('Error generating PDF:', error);
}
};
return (
<div>
{/* Input HTML content */}
<textarea onChange={(e) => convertHTMLToPDF(e.target.value)} />
</div>
);
};
export default HTMLToPDFComponent;- PDF Oluşturmayı İşleme: React bileşenlerinizde PDF oluşturmayı, manipülasyonu ve kaydetmeyi işlemek için IronPDF'un işlevselliğini kullanın. IronPDF'un HTML dizelerini, URL'leri veya görüntüleri PDF'e dönüştürme yöntemlerini kullanabilirsiniz.
- PDF'leri Görüntüleme: IronPDF kullanarak PDF oluşturduktan sonra, React uygulamanızda PDF belgelerini görüntülemek için uygun bileşenleri veya kütüphaneleri kullanarak render edebilirsiniz.
import React from 'react';
const PDFViewerComponent = () => {
return (
<div>
{/* Render PDF using appropriate component or library */}
<iframe src="generated_pdf.pdf" width="100%" height="600px" title="PDF Viewer" />
</div>
);
};
export default PDFViewerComponent;import React from 'react';
const PDFViewerComponent = () => {
return (
<div>
{/* Render PDF using appropriate component or library */}
<iframe src="generated_pdf.pdf" width="100%" height="600px" title="PDF Viewer" />
</div>
);
};
export default PDFViewerComponent;IronPDF ile geliştiriciler, farklı kaynaklardan profesyonel kalitede PDF belgeleri verimli bir şekilde oluşturabilir, onları özel gereksinimlere göre özelleştirebilir ve .NET uygulamalarına PDF oluşturma yeteneklerini sorunsuz bir şekilde entegre edebilir. IronPDF ayrıca CSS, JavaScript ve özel fontlar gibi gelişmiş özellikleri destekleyerek, oluşturulan PDF dosyalarınızın uygulamanızın tasarım ve gereksinimlerine uyumlu olmasını sağlar.
Sonuç
Bu makalede, React-pdf kütüphanesini kullanarak React'te HTML'yi PDF'e dönüştürme sürecini ele aldık. PDF dosyalarını React-pdf kullanarak nasıl oluşturup stilize edeceğinizi ve daha karmaşık PDF belgeleri oluşturmak için ek seçenekleri açıkladık.
Bu kılavuzu takip ederek, React uygulamalarınızda PDF dosyaları oluşturmanın nasıl yapıldığını tam olarak anlayarak, yüksek kaliteli PDF'ler oluşturabilir ve çeşitli kullanım senaryolarının ihtiyaçlarını karşılayabilirsiniz.
IronPDF, kütüphaneyi test etmenize ve bir satın alma taahhüdü öncesinde ihtiyaçlarınıza uygun olup olmadığını belirlemenize olanak sağlayan bir ücretsiz deneme sürümü sunar. Deneme süresinden sonra, IronPDF satın alma lisansları $799 ile başlar, bu da öncelikli destek ve güncellemeyi içerir. Ek olarak, IronPDF C# .NET, Java ve Python gibi diğer diller için de mevcuttur. Node.js için IronPDF ile başlayarak IronPDF kütüphanesini indirin ve deneyin.








