⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 text2pdfdlg.cpp

📁 将TXT文件转换成PDF文件,从CODEPROJECTS网站上得来的,很好用!
💻 CPP
字号:
// Text2PDFDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Text2PDF.h"
#include "Text2PDFDlg.h"

#include "PDFLib.hpp"
#include "CommonDef.h"
#include "Options.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

void PreparePDFPage(int Page, float* width, float* height);
CString GetEffect(int iEffect);
CString GetAction(int iAction);
CString GetMode(int iMode);
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CText2PDFDlg dialog

CText2PDFDlg::CText2PDFDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CText2PDFDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CText2PDFDlg)
	m_FileName = _T("");
	m_Font = _T("");
	m_Text = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	ZeroMemory(&FontSpec, sizeof(FontSpec));
	ZeroMemory(&PageSpec, sizeof(PageSpec));
}

void CText2PDFDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CText2PDFDlg)
	DDX_Control(pDX, IDC_CONVERT_PROGRESS, m_Progress);
	DDX_Text(pDX, IDC_FILENAME, m_FileName);
	DDX_Text(pDX, IDC_FONT, m_Font);
	DDX_Text(pDX, IDC_TEXT_FILE, m_Text);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CText2PDFDlg, CDialog)
	//{{AFX_MSG_MAP(CText2PDFDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_CLOSE, OnClose)
	ON_BN_CLICKED(IDC_CONVERT, OnConvert)
	ON_BN_CLICKED(IDC_FILE_SELECT, OnFileSelect)
	ON_BN_CLICKED(IDC_FONT_SELECT, OnFontSelect)
	ON_BN_CLICKED(IDC_OPTIONS, OnOptions)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CText2PDFDlg message handlers

BOOL CText2PDFDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	FontSpec.FontSize = 12;
	CClientDC dc(this);
	SetMapMode(dc.m_hDC, MM_TEXT);
	FontSpec.lf.lfHeight=-MulDiv(12, GetDeviceCaps(dc.m_hDC, LOGPIXELSY), 72);
	strcpy(FontSpec.lf.lfFaceName, "Arial");
	m_Font.Format("%s, %d", FontSpec.lf.lfFaceName, FontSpec.FontSize);

	PageSpec.Bottom=MARGIN_BOTTOM;
	PageSpec.Left=MARGIN_LEFT;
	PageSpec.Right=MARGIN_RIGHT;
	PageSpec.Top=MARGIN_TOP;
	PageSpec.Effect=DEFAULT_EFFECT;
	PageSpec.OpenAction=DEFAULT_OPEN_ACTION;
	PageSpec.OpenMode=DEFAULT_OPEN_MODE;
	PageSpec.PageSize=DEFAULT_PAGE;
	PageSpec.Launch=TRUE;

	UpdateData(FALSE);
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CText2PDFDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CText2PDFDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CText2PDFDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CText2PDFDlg::OnClose() 
{
	OnOK();	
}

void CText2PDFDlg::OnFileSelect() 
{
	CFileDialog cFileDlg (TRUE, _T("txt"), (LPCTSTR) NULL, 
		OFN_ENABLESIZING | OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_LONGNAMES | 
		OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_CREATEPROMPT, 
		_T("Text Files (*.txt)|*.txt|All Files (*.*)|*.*|"), this);

	cFileDlg.m_ofn.lpstrTitle = _T("Open Text File");
		
	if (cFileDlg.DoModal()==IDOK)
	{
		m_FileName=cFileDlg.GetPathName();
		UpdateTextFile(m_FileName);
		m_PDFName=m_FileName;
		m_PDFName=m_PDFName.Left(m_PDFName.ReverseFind('.'))+CString(".pdf");
		UpdateData(FALSE);
	}

	CheckConvertBtn();
}

void CText2PDFDlg::OnFontSelect() 
{
	CFontDialog cFontDlg(&FontSpec.lf);
	
	if (cFontDlg.DoModal()==IDOK)
	{
		m_Font.Format("%s, %d", cFontDlg.GetFaceName().GetBuffer(0), 
								cFontDlg.GetSize()/10);
		
		cFontDlg.GetCurrentFont(&FontSpec.lf);
		FontSpec.FontSize=cFontDlg.GetSize()/10;
		UpdateData(FALSE);
	}

	CheckConvertBtn();
}

void CText2PDFDlg::UpdateTextFile(CString FileName)
{
	CFileStatus fs;
	CFile::GetStatus(FileName, fs);

	char* Buf=new char[fs.m_size];
	ZeroMemory(Buf, fs.m_size);

	FILE* fp;
	fp=fopen(FileName, "rt");
	fread(Buf, fs.m_size, 1, fp);
	fclose(fp);

	m_Text=Buf;
	m_Text.Replace("\n","\r\n");
	
	delete [] Buf;
	UpdateData(FALSE);
}

void CText2PDFDlg::CheckConvertBtn()
{
	UpdateData(TRUE);
	
	if ((stricmp(FontSpec.lf.lfFaceName, "")==0) || m_FileName.IsEmpty())
	{
		GetDlgItem(IDC_CONVERT)->EnableWindow(FALSE);
	}
	else
	{
		GetDlgItem(IDC_CONVERT)->EnableWindow(TRUE);
	}
}

void CText2PDFDlg::OnOptions() 
{
	COptions opt;
	opt.SetParameter(PageSpec);

	if (opt.DoModal()==IDOK)
	{
		PageSpec=opt.GetParameter();
	}
}

void CText2PDFDlg::OnConvert() 
{
	PDFlib pdf;
	pdf.set_parameter("compatibility", "1.4");	//Compatible for Acrobat 5
	
	if (pdf.open(m_PDFName.GetBuffer(0))==-1)
	{
		AfxMessageBox("Can not create PDF file.\n"
			"May be file opened by another process", MB_ICONERROR);
		return;
	}
	
	pdf.set_info("Creator", "Text2PDF");
    pdf.set_info("Author", "A. Riazi");
    pdf.set_info("Title","Text File Converted to PDF");
	pdf.set_info("Subject","Text2PDF Convertor");
	pdf.set_info("Keywords","Codeproject.com");
		
	float width, height;
	PreparePDFPage(PageSpec.PageSize, &width, &height);

	float PageHeight=0.0, PageWidth=0.0;

	pdf.begin_page(width, height);
	
	pdf.add_note(width - 50, height - 50, width + 150, height - 200, 
		"This pdf file was created by Text2PDF, "
		"a free utility written by A. Riazi (a.riazi@misbah3com.com).\r\n\r\n"
		"Source code available from codeproject.com\r\n ", "Text2PDF", "note", false);

	//Font will be embedded in PDF
	int font=pdf.findfont(FontSpec.lf.lfFaceName, "winansi", 1);	
	pdf.setfont(font, FontSpec.FontSize);

	pdf.set_text_pos(PageSpec.Left, height - PageSpec.Top);
		
	CString Line, Text;
	Text=m_Text;
	Text.Replace("\r\n","\r");

	float descender=pdf.get_value("descender", font);
	float LineHeight=(1-descender)*FontSpec.FontSize;

	int iWordIndex=0;
	int iProgress=0;

	m_Progress.SetRange32(0, m_Text.GetLength());

	while (!Text.IsEmpty())
	{
		while (PageWidth<=width)
		{
			iWordIndex=Text.Find(' ', iWordIndex);
			
			if (iWordIndex!=-1)
				Line=Text.Left(iWordIndex++);
			else
			{
				Line=Text;
				break;
			}
			
			PageWidth=pdf.stringwidth(Line.GetBuffer(0),
				font, FontSpec.FontSize);
		}

		iWordIndex=Line.Find('\r');
		if (iWordIndex!=-1)		//enter found (carriage return)
		{
			Line=Line.Left(iWordIndex);
			Text=Text.Right(Text.GetLength() - Line.GetLength() - 1);
		}
		else
		{
			iWordIndex=Line.ReverseFind(' ');
			if (iWordIndex!=-1)		//space found
			{
				if (pdf.stringwidth(Line.GetBuffer(0),
							font, FontSpec.FontSize)>width)
				{
					Line=Line.Left(iWordIndex);	//with space character
					Text=Text.Right(Text.GetLength() - iWordIndex);
				}
				else
				{
					Line=Text;
					Text="";
				}
			}
			else
			{
				Text=Text.Right(Text.GetLength() - Line.GetLength());
			}
		}

		iWordIndex=0;
		iProgress+=Line.GetLength();

		m_Progress.SetPos(iProgress);

		pdf.continue_text(Line.GetBuffer(0));
						
		PageWidth=0;
		PageHeight=pdf.get_value("texty",0.0);

		if (PageHeight<PageSpec.Bottom)
		{
			pdf.end_page();
			pdf.begin_page(width, height);
			pdf.setfont(font, FontSpec.FontSize);
			pdf.set_text_pos(PageSpec.Left, height - PageSpec.Top);			
		}

		Line="";
	}
	
	pdf.end_page();
	
	//Open Action
	CString Action=GetAction(PageSpec.OpenAction);
	pdf.set_parameter("openaction", Action.GetBuffer(0));

	//Open Mode
	CString Mode=GetMode(PageSpec.OpenMode);
	pdf.set_parameter("openmode", Mode.GetBuffer(0));

	//Effects
	CString Effect=GetEffect(PageSpec.Effect);
	pdf.set_parameter("transition",Effect.GetBuffer(0));

	pdf.close();

	//work is done.
	m_Progress.SetPos(0);

	if (PageSpec.Launch)
		ShellExecute(NULL, "open", m_PDFName, NULL, NULL, SW_SHOW);
}

void PreparePDFPage(int Page, float* width, float* height)
{
	switch (Page)
	{
		case 0:		//A0
			*width=a0_width;
			*height=a0_height;
			break;

		case 1:		//A1
			*width=a1_width;
			*height=a1_height;
			break;

		case 2:		//A2
			*width=a2_width;
			*height=a2_height;
			break;

		case 3:		//A3
			*width=a3_width;
			*height=a3_height;
			break;

		case 4:		//A4
			*width=a4_width;
			*height=a4_height;
			break;

		case 5:		//A5
			*width=a5_width;
			*height=a5_height;
			break;

		case 6:		//A6
			*width=a6_width;
			*height=a6_height;
			break;

		case 7:		//B5
			*width=b5_width;
			*height=b5_height;
			break;

		case 8:		//letter
			*width=letter_width;
			*height=letter_height;
			break;

		case 9:		//legal
			*width=legal_width;
			*height=legal_height;
			break;

		case 10:	//ledger
			*width=ledger_width;
			*height=ledger_height;
			break;
	}
}

CString GetEffect(int iEffect)
{
	CString Result;
	switch (iEffect)
	{
		case 0:
			Result="split";
			break;

		case 1:
			Result="blinds";
			break;

		case 2:
			Result="box";
			break;

		case 3:
			Result="wipe";
			break;

		case 4:
			Result="dissolve";
			break;

		case 5:
			Result="glitter";
			break;

		case 6:
			Result="replace";
			break;
	}

	return Result;
}

CString GetAction(int iAction)
{
	CString Result;
	switch (iAction)
	{
		case 0:
			Result="retain";
			break;

		case 1:
			Result="fitpage";
			break;

		case 2:
			Result="fitwidth";
			break;

		case 3:
			Result="fitheight";
			break;

		case 4:
			Result="fitbbox";
			break;
	}

	return Result;
}

CString GetMode(int iMode)
{
	CString Result;
	switch (iMode)
	{
		case 0:
			Result="none";
			break;

		case 1:
			Result="bookmarks";
			break;

		case 2:
			Result="thumbnails";
			break;

		case 3:
			Result="fullscreen";
			break;
	}

	return Result;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -