首页 > 代码库 > 文本导出到pdf文件

文本导出到pdf文件

   程序中数据导出是经常有的需求,今天学习把文本导出到pdf文件。主要是用QPrinter,QPainter

TextEditToPdf::TextEditToPdf(QWidget *parent, Qt::WFlags flags)
	: QDialog(parent, flags)
{
	ui.setupUi(this);
	int ret = connect(ui.m_pExportBtn,SIGNAL(clicked()),this,SLOT(exportSlot()));
}

TextEditToPdf::~TextEditToPdf()
{

}

void TextEditToPdf::exportSlot()
{
	
	QTextDocument  textDocument;
	QPrinter printer(QPrinter::ScreenResolution);
	printer.setPaperSize(QPrinter::A4);
	printer.setPageMargins(30,30,30,30,QPrinter::DevicePixel);
	printer.setOutputFormat(QPrinter::PdfFormat);
	printer.setOutputFileName(QString("11") + ".pdf");
	QPainter painter( &printer );
	QFont font;
	font.setPixelSize(15);
	painter.setFont(font);
	QTextOption textOption( Qt::AlignCenter);
	QPen pen;
	pen.setColor(Qt::black);
	pen.setWidth(1);
	painter.setPen(pen);

	int paperWidth = printer.width();
	int paperHeigth = printer.height();

	painter.drawText( QRect(QPoint( 30,30),QPoint(paperWidth - 30,paperHeigth- 20)),ui.m_pTextEdit->toPlainText (),textOption);
	textDocument.print(&printer);

}